]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
Merge remote-tracking branch 'origin/mdb.RE/0.9'
[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-2016 The OpenLDAP Foundation.
6  * Portions Copyright 2003 by IBM Corporation.
7  * Portions Copyright 2003-2008 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 #ifdef ENABLE_REWRITE
35 #include "rewrite.h"
36 #define SUFFIXM_CTX     "<suffix massage>"
37 #endif
38
39 #define UUIDLEN 16
40
41 struct nonpresent_entry {
42         struct berval *npe_name;
43         struct berval *npe_nname;
44         LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
45 };
46
47 typedef struct cookie_state {
48         ldap_pvt_thread_mutex_t cs_mutex;
49         struct berval *cs_vals;
50         int *cs_sids;
51         int     cs_num;
52         int cs_age;
53         int cs_ref;
54
55         /* pending changes, not yet committed */
56         ldap_pvt_thread_mutex_t cs_pmutex;
57         struct berval *cs_pvals;
58         int *cs_psids;
59         int     cs_pnum;
60 } cookie_state;
61
62 #define SYNCDATA_DEFAULT        0       /* entries are plain LDAP entries */
63 #define SYNCDATA_ACCESSLOG      1       /* entries are accesslog format */
64 #define SYNCDATA_CHANGELOG      2       /* entries are changelog format */
65
66 #define SYNCLOG_LOGGING         0       /* doing a log-based update */
67 #define SYNCLOG_FALLBACK        1       /* doing a full refresh */
68
69 #define RETRYNUM_FOREVER        (-1)    /* retry forever */
70 #define RETRYNUM_TAIL           (-2)    /* end of retrynum array */
71 #define RETRYNUM_VALID(n)       ((n) >= RETRYNUM_FOREVER)       /* valid retrynum */
72 #define RETRYNUM_FINITE(n)      ((n) > RETRYNUM_FOREVER)        /* not forever */
73
74 typedef struct syncinfo_s {
75         struct syncinfo_s       *si_next;
76         BackendDB               *si_be;
77         BackendDB               *si_wbe;
78         struct re_s             *si_re;
79         int                     si_rid;
80         char                    si_ridtxt[ STRLENOF("rid=999") + 1 ];
81         slap_bindconf           si_bindconf;
82         struct berval           si_base;
83         struct berval           si_logbase;
84         struct berval           si_filterstr;
85         struct berval           si_logfilterstr;
86         Filter                  *si_filter;
87         Filter                  *si_logfilter;
88         struct berval           si_contextdn;
89         int                     si_scope;
90         int                     si_attrsonly;
91         char                    *si_anfile;
92         AttributeName           *si_anlist;
93         AttributeName           *si_exanlist;
94         char                    **si_attrs;
95         char                    **si_exattrs;
96         int                     si_allattrs;
97         int                     si_allopattrs;
98         int                     si_schemachecking;
99         int                     si_type;        /* the active type */
100         int                     si_ctype;       /* the configured type */
101         time_t                  si_interval;
102         time_t                  *si_retryinterval;
103         int                     *si_retrynum_init;
104         int                     *si_retrynum;
105         struct sync_cookie      si_syncCookie;
106         cookie_state            *si_cookieState;
107         int                     si_cookieAge;
108         int                     si_manageDSAit;
109         int                     si_slimit;
110         int                     si_tlimit;
111         int                     si_refreshDelete;
112         int                     si_refreshPresent;
113         int                     si_refreshDone;
114         int                     si_refreshCount;
115         time_t          si_refreshBeg;
116         time_t          si_refreshEnd;
117         OpExtra         *si_refreshTxn;
118         int                     si_syncdata;
119         int                     si_logstate;
120         int                     si_lazyCommit;
121         int                     si_got;
122         int                     si_strict_refresh;      /* stop listening during fallback refresh */
123         int                     si_too_old;
124         ber_int_t       si_msgid;
125         Avlnode                 *si_presentlist;
126         LDAP                    *si_ld;
127         Connection              *si_conn;
128         LDAP_LIST_HEAD(np, nonpresent_entry)    si_nonpresentlist;
129 #ifdef ENABLE_REWRITE
130         struct rewrite_info *si_rewrite;
131         struct berval   si_suffixm;
132 #endif
133         ldap_pvt_thread_mutex_t si_mutex;
134 } syncinfo_t;
135
136 static int syncuuid_cmp( const void *, const void * );
137 static int presentlist_insert( syncinfo_t* si, struct berval *syncUUID );
138 static void presentlist_delete( Avlnode **av, struct berval *syncUUID );
139 static char *presentlist_find( Avlnode *av, struct berval *syncUUID );
140 static int presentlist_free( Avlnode *av );
141 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct sync_cookie *, int );
142 static int syncrepl_message_to_op(
143                                         syncinfo_t *, Operation *, LDAPMessage * );
144 static int syncrepl_message_to_entry(
145                                         syncinfo_t *, Operation *, LDAPMessage *,
146                                         Modifications **, Entry **, int, struct berval* );
147 static int syncrepl_entry(
148                                         syncinfo_t *, Operation*, Entry*,
149                                         Modifications**,int, struct berval*,
150                                         struct berval *cookieCSN );
151 static int syncrepl_updateCookie(
152                                         syncinfo_t *, Operation *,
153                                         struct sync_cookie * );
154 static struct berval * slap_uuidstr_from_normalized(
155                                         struct berval *, struct berval *, void * );
156 static int syncrepl_add_glue_ancestors(
157         Operation* op, Entry *e );
158
159 /* delta-mmr overlay handler */
160 static int syncrepl_op_modify( Operation *op, SlapReply *rs );
161
162 /* callback functions */
163 static int dn_callback( Operation *, SlapReply * );
164 static int nonpresent_callback( Operation *, SlapReply * );
165 static int null_callback( Operation *, SlapReply * );
166
167 static AttributeDescription *sync_descs[4];
168
169 /* delta-mmr */
170 static AttributeDescription *ad_reqMod, *ad_reqDN;
171
172 typedef struct logschema {
173         struct berval ls_dn;
174         struct berval ls_req;
175         struct berval ls_mod;
176         struct berval ls_newRdn;
177         struct berval ls_delRdn;
178         struct berval ls_newSup;
179 } logschema;
180
181 static logschema changelog_sc = {
182         BER_BVC("targetDN"),
183         BER_BVC("changeType"),
184         BER_BVC("changes"),
185         BER_BVC("newRDN"),
186         BER_BVC("deleteOldRDN"),
187         BER_BVC("newSuperior")
188 };
189
190 static logschema accesslog_sc = {
191         BER_BVC("reqDN"),
192         BER_BVC("reqType"),
193         BER_BVC("reqMod"),
194         BER_BVC("reqNewRDN"),
195         BER_BVC("reqDeleteOldRDN"),
196         BER_BVC("reqNewSuperior")
197 };
198
199 static const char *
200 syncrepl_state2str( int state )
201 {
202         switch ( state ) {
203         case LDAP_SYNC_PRESENT:
204                 return "PRESENT";
205
206         case LDAP_SYNC_ADD:
207                 return "ADD";
208
209         case LDAP_SYNC_MODIFY:
210                 return "MODIFY";
211
212         case LDAP_SYNC_DELETE:
213                 return "DELETE";
214         }
215
216         return "UNKNOWN";
217 }
218
219 static slap_overinst syncrepl_ov;
220
221 static void
222 init_syncrepl(syncinfo_t *si)
223 {
224         int i, j, k, l, n;
225         char **attrs, **exattrs;
226
227         if ( !syncrepl_ov.on_bi.bi_type ) {
228                 syncrepl_ov.on_bi.bi_type = "syncrepl";
229                 syncrepl_ov.on_bi.bi_op_modify = syncrepl_op_modify;
230                 overlay_register( &syncrepl_ov );
231         }
232
233         /* delta-MMR needs the overlay, nothing else does.
234          * This must happen before accesslog overlay is configured.
235          */
236         if ( si->si_syncdata &&
237                 !overlay_is_inst( si->si_be, syncrepl_ov.on_bi.bi_type )) {
238                 overlay_config( si->si_be, syncrepl_ov.on_bi.bi_type, -1, NULL, NULL );
239                 if ( !ad_reqMod ) {
240                         const char *text;
241                         logschema *ls = &accesslog_sc;
242
243                         slap_bv2ad( &ls->ls_mod, &ad_reqMod, &text );
244                         slap_bv2ad( &ls->ls_dn, &ad_reqDN, &text );
245                 }
246         }
247
248         if ( !sync_descs[0] ) {
249                 sync_descs[0] = slap_schema.si_ad_objectClass;
250                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
251                 sync_descs[2] = slap_schema.si_ad_entryCSN;
252                 sync_descs[3] = NULL;
253         }
254
255         if ( si->si_allattrs && si->si_allopattrs )
256                 attrs = NULL;
257         else
258                 attrs = anlist2attrs( si->si_anlist );
259
260         if ( attrs ) {
261                 if ( si->si_allattrs ) {
262                         i = 0;
263                         while ( attrs[i] ) {
264                                 if ( !is_at_operational( at_find( attrs[i] ) ) ) {
265                                         for ( j = i; attrs[j] != NULL; j++ ) {
266                                                 if ( j == i )
267                                                         ch_free( attrs[i] );
268                                                 attrs[j] = attrs[j+1];
269                                         }
270                                 } else {
271                                         i++;
272                                 }
273                         }
274                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
275                         attrs[i] = ch_strdup("*");
276                         attrs[i + 1] = NULL;
277
278                 } else if ( si->si_allopattrs ) {
279                         i = 0;
280                         while ( attrs[i] ) {
281                                 if ( is_at_operational( at_find( attrs[i] ) ) ) {
282                                         for ( j = i; attrs[j] != NULL; j++ ) {
283                                                 if ( j == i )
284                                                         ch_free( attrs[i] );
285                                                 attrs[j] = attrs[j+1];
286                                         }
287                                 } else {
288                                         i++;
289                                 }
290                         }
291                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
292                         attrs[i] = ch_strdup("+");
293                         attrs[i + 1] = NULL;
294                 }
295
296                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
297                         j = 0;
298                         while ( attrs[j] ) {
299                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
300                                         for ( k = j; attrs[k] != NULL; k++ ) {
301                                                 if ( k == j )
302                                                         ch_free( attrs[k] );
303                                                 attrs[k] = attrs[k+1];
304                                         }
305                                 } else {
306                                         j++;
307                                 }
308                         }
309                 }
310
311                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
312
313                 if ( si->si_allopattrs ) {
314                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ) );
315                 } else {
316                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ) );
317                 }
318
319                 /* Add Attributes */
320                 if ( si->si_allopattrs ) {
321                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
322                 } else {
323                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
324                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
325                         }
326                 }
327                 attrs[ n ] = NULL;
328
329         } else {
330
331                 i = 0;
332                 if ( si->si_allattrs == si->si_allopattrs ) {
333                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
334                         attrs[i++] = ch_strdup( "*" );
335                         attrs[i++] = ch_strdup( "+" );
336                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
337                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
338                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
339                         attrs[i++] = ch_strdup( "*" );
340                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
341                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
342                         }
343                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
344                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
345                         attrs[i++] = ch_strdup( "+" );
346                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
347                 }
348                 attrs[i] = NULL;
349         }
350         
351         si->si_attrs = attrs;
352
353         exattrs = anlist2attrs( si->si_exanlist );
354
355         if ( exattrs ) {
356                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
357
358                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
359                         j = 0;
360                         while ( exattrs[j] != NULL ) {
361                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
362                                         ch_free( exattrs[j] );
363                                         for ( k = j; exattrs[k] != NULL; k++ ) {
364                                                 exattrs[k] = exattrs[k+1];
365                                         }
366                                 } else {
367                                         j++;
368                                 }
369                         }
370                 }
371
372                 for ( i = 0; exattrs[i] != NULL; i++ ) {
373                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
374                                 ObjectClass     *oc;
375                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
376                                         k = 0;
377                                         while ( oc->soc_required[k] ) {
378                                                 if ( !strcmp( exattrs[i],
379                                                          oc->soc_required[k]->sat_cname.bv_val ) ) {
380                                                         ch_free( exattrs[i] );
381                                                         for ( l = i; exattrs[l]; l++ ) {
382                                                                 exattrs[l] = exattrs[l+1];
383                                                         }
384                                                 } else {
385                                                         k++;
386                                                 }
387                                         }
388                                 }
389                         }
390                 }
391
392                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
393
394                 if ( i != n )
395                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *) );
396         }
397
398         si->si_exattrs = exattrs;       
399 }
400
401 static int
402 ldap_sync_search(
403         syncinfo_t *si,
404         void *ctx )
405 {
406         BerElementBuffer berbuf;
407         BerElement *ber = (BerElement *)&berbuf;
408         LDAPControl c[3], *ctrls[4];
409         int rc;
410         int rhint;
411         char *base;
412         char **attrs, *lattrs[8];
413         char *filter;
414         int attrsonly;
415         int scope;
416
417         /* setup LDAP SYNC control */
418         ber_init2( ber, NULL, LBER_USE_DER );
419         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
420
421         /* If we're using a log but we have no state, then fallback to
422          * normal mode for a full refresh.
423          */
424         if ( si->si_syncdata && !si->si_syncCookie.numcsns ) {
425                 si->si_logstate = SYNCLOG_FALLBACK;
426         }
427
428         /* Use the log parameters if we're in log mode */
429         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
430                 logschema *ls;
431                 if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
432                         ls = &accesslog_sc;
433                 else
434                         ls = &changelog_sc;
435                 lattrs[0] = ls->ls_dn.bv_val;
436                 lattrs[1] = ls->ls_req.bv_val;
437                 lattrs[2] = ls->ls_mod.bv_val;
438                 lattrs[3] = ls->ls_newRdn.bv_val;
439                 lattrs[4] = ls->ls_delRdn.bv_val;
440                 lattrs[5] = ls->ls_newSup.bv_val;
441                 lattrs[6] = slap_schema.si_ad_entryCSN->ad_cname.bv_val;
442                 lattrs[7] = NULL;
443
444                 rhint = 0;
445                 base = si->si_logbase.bv_val;
446                 filter = si->si_logfilterstr.bv_val;
447                 attrs = lattrs;
448                 attrsonly = 0;
449                 scope = LDAP_SCOPE_SUBTREE;
450         } else {
451                 rhint = 1;
452                 base = si->si_base.bv_val;
453                 filter = si->si_filterstr.bv_val;
454                 attrs = si->si_attrs;
455                 attrsonly = si->si_attrsonly;
456                 scope = si->si_scope;
457         }
458         if ( si->si_syncdata && si->si_logstate == SYNCLOG_FALLBACK ) {
459                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
460         } else {
461                 si->si_type = si->si_ctype;
462         }
463
464         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
465         {
466                 ber_printf( ber, "{eOb}",
467                         abs(si->si_type), &si->si_syncCookie.octet_str, rhint );
468         } else {
469                 ber_printf( ber, "{eb}",
470                         abs(si->si_type), rhint );
471         }
472
473         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 ) ) == -1 ) {
474                 ber_free_buf( ber );
475                 return rc;
476         }
477
478         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
479         c[0].ldctl_iscritical = si->si_type < 0;
480         ctrls[0] = &c[0];
481
482         c[1].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
483         BER_BVZERO( &c[1].ldctl_value );
484         c[1].ldctl_iscritical = 1;
485         ctrls[1] = &c[1];
486
487         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
488                 c[2].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
489                 c[2].ldctl_value = si->si_bindconf.sb_authzId;
490                 c[2].ldctl_iscritical = 1;
491                 ctrls[2] = &c[2];
492                 ctrls[3] = NULL;
493         } else {
494                 ctrls[2] = NULL;
495         }
496
497         rc = ldap_search_ext( si->si_ld, base, scope, filter, attrs, attrsonly,
498                 ctrls, NULL, NULL, si->si_slimit, &si->si_msgid );
499         ber_free_buf( ber );
500         return rc;
501 }
502
503 static int
504 check_syncprov(
505         Operation *op,
506         syncinfo_t *si )
507 {
508         AttributeName at[2];
509         Attribute a = {0};
510         Entry e = {0};
511         SlapReply rs = {REP_SEARCH};
512         int i, j, changed = 0;
513
514         /* Look for contextCSN from syncprov overlay. If
515          * there's no overlay, this will be a no-op. That means
516          * this is a pure consumer, so local changes will not be
517          * allowed, and all changes will already be reflected in
518          * the cookieState.
519          */
520         a.a_desc = slap_schema.si_ad_contextCSN;
521         e.e_attrs = &a;
522         e.e_name = si->si_contextdn;
523         e.e_nname = si->si_contextdn;
524         at[0].an_name = a.a_desc->ad_cname;
525         at[0].an_desc = a.a_desc;
526         BER_BVZERO( &at[1].an_name );
527         rs.sr_entry = &e;
528         rs.sr_flags = REP_ENTRY_MODIFIABLE;
529         rs.sr_attrs = at;
530         op->o_req_dn = e.e_name;
531         op->o_req_ndn = e.e_nname;
532
533         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
534         i = backend_operational( op, &rs );
535         if ( i == LDAP_SUCCESS && a.a_nvals ) {
536                 int num = a.a_numvals;
537                 /* check for differences */
538                 if ( num != si->si_cookieState->cs_num ) {
539                         changed = 1;
540                 } else {
541                         for ( i=0; i<num; i++ ) {
542                                 if ( ber_bvcmp( &a.a_nvals[i],
543                                         &si->si_cookieState->cs_vals[i] )) {
544                                         changed = 1;
545                                         break;
546                                 }
547                         }
548                 }
549                 if ( changed ) {
550                         ber_bvarray_free( si->si_cookieState->cs_vals );
551                         ch_free( si->si_cookieState->cs_sids );
552                         si->si_cookieState->cs_num = num;
553                         si->si_cookieState->cs_vals = a.a_nvals;
554                         si->si_cookieState->cs_sids = slap_parse_csn_sids( a.a_nvals,
555                                 num, NULL );
556                         si->si_cookieState->cs_age++;
557                 } else {
558                         ber_bvarray_free( a.a_nvals );
559                 }
560                 ber_bvarray_free( a.a_vals );
561         }
562         /* See if the cookieState has changed due to anything outside
563          * this particular consumer. That includes other consumers in
564          * the same context, or local changes detected above.
565          */
566         if ( si->si_cookieState->cs_num > 0 && si->si_cookieAge !=
567                 si->si_cookieState->cs_age ) {
568                 if ( !si->si_syncCookie.numcsns ) {
569                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
570                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
571                                 si->si_cookieState->cs_vals, NULL );
572                         changed = 1;
573                 } else {
574                         for (i=0; !BER_BVISNULL( &si->si_syncCookie.ctxcsn[i] ); i++) {
575                                 /* bogus, just dup everything */
576                                 if ( si->si_syncCookie.sids[i] == -1 ) {
577                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
578                                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
579                                                 si->si_cookieState->cs_vals, NULL );
580                                         changed = 1;
581                                         break;
582                                 }
583                                 for (j=0; j<si->si_cookieState->cs_num; j++) {
584                                         if ( si->si_syncCookie.sids[i] !=
585                                                 si->si_cookieState->cs_sids[j] )
586                                                 continue;
587                                         if ( bvmatch( &si->si_syncCookie.ctxcsn[i],
588                                                 &si->si_cookieState->cs_vals[j] ))
589                                                 break;
590                                         ber_bvreplace( &si->si_syncCookie.ctxcsn[i],
591                                                 &si->si_cookieState->cs_vals[j] );
592                                         changed = 1;
593                                         break;
594                                 }
595                         }
596                 }
597         }
598         if ( changed ) {
599                 si->si_cookieAge = si->si_cookieState->cs_age;
600                 ch_free( si->si_syncCookie.octet_str.bv_val );
601                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
602                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
603                         si->si_syncCookie.sid );
604                 ch_free( si->si_syncCookie.sids );
605                 slap_reparse_sync_cookie( &si->si_syncCookie, op->o_tmpmemctx );
606         }
607         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
608         return changed;
609 }
610
611 static int
612 do_syncrep1(
613         Operation *op,
614         syncinfo_t *si )
615 {
616         int     rc;
617         int cmdline_cookie_found = 0;
618
619         struct sync_cookie      *sc = NULL;
620 #ifdef HAVE_TLS
621         void    *ssl;
622 #endif
623
624         rc = slap_client_connect( &si->si_ld, &si->si_bindconf );
625         if ( rc != LDAP_SUCCESS ) {
626                 goto done;
627         }
628         op->o_protocol = LDAP_VERSION3;
629
630         /* Set SSF to strongest of TLS, SASL SSFs */
631         op->o_sasl_ssf = 0;
632         op->o_tls_ssf = 0;
633         op->o_transport_ssf = 0;
634 #ifdef HAVE_TLS
635         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
636                 == LDAP_SUCCESS && ssl != NULL )
637         {
638                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
639         }
640 #endif /* HAVE_TLS */
641         {
642                 ber_len_t ssf; /* ITS#5403, 3864 LDAP_OPT_X_SASL_SSF probably ought
643                                                   to use sasl_ssf_t but currently uses ber_len_t */
644                 if ( ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &ssf )
645                         == LDAP_SUCCESS )
646                         op->o_sasl_ssf = ssf;
647         }
648         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
649                 ?  op->o_sasl_ssf : op->o_tls_ssf;
650
651         ldap_set_option( si->si_ld, LDAP_OPT_TIMELIMIT, &si->si_tlimit );
652
653         rc = LDAP_DEREF_NEVER;  /* actually could allow DEREF_FINDING */
654         ldap_set_option( si->si_ld, LDAP_OPT_DEREF, &rc );
655
656         ldap_set_option( si->si_ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF );
657
658         si->si_syncCookie.rid = si->si_rid;
659
660         /* whenever there are multiple data sources possible, advertise sid */
661         si->si_syncCookie.sid = ( SLAP_MULTIMASTER( si->si_be ) || si->si_be != si->si_wbe ) ?
662                 slap_serverID : -1;
663
664         /* We've just started up, or the remote server hasn't sent us
665          * any meaningful state.
666          */
667         if ( !si->si_syncCookie.ctxcsn ) {
668                 int i;
669
670                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
671                         if ( si->si_rid == sc->rid ) {
672                                 cmdline_cookie_found = 1;
673                                 break;
674                         }
675                 }
676
677                 if ( cmdline_cookie_found ) {
678                         /* cookie is supplied in the command line */
679
680                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
681
682                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
683                         si->si_syncCookie.octet_str = sc->octet_str;
684                         ch_free( sc );
685                         /* ctxcsn wasn't parsed yet, do it now */
686                         slap_parse_sync_cookie( &si->si_syncCookie, NULL );
687                 } else {
688                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
689                         if ( !si->si_cookieState->cs_num ) {
690                                 /* get contextCSN shadow replica from database */
691                                 BerVarray csn = NULL;
692                                 void *ctx = op->o_tmpmemctx;
693
694                                 op->o_req_ndn = si->si_contextdn;
695                                 op->o_req_dn = op->o_req_ndn;
696
697                                 /* try to read stored contextCSN */
698                                 op->o_tmpmemctx = NULL;
699                                 backend_attribute( op, NULL, &op->o_req_ndn,
700                                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
701                                 op->o_tmpmemctx = ctx;
702                                 if ( csn ) {
703                                         si->si_cookieState->cs_vals = csn;
704                                         for (i=0; !BER_BVISNULL( &csn[i] ); i++);
705                                         si->si_cookieState->cs_num = i;
706                                         si->si_cookieState->cs_sids = slap_parse_csn_sids( csn, i, NULL );
707                                         slap_sort_csn_sids( csn, si->si_cookieState->cs_sids, i, NULL );
708                                 }
709                         }
710                         if ( si->si_cookieState->cs_num ) {
711                                 ber_bvarray_free( si->si_syncCookie.ctxcsn );
712                                 if ( ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
713                                         si->si_cookieState->cs_vals, NULL )) {
714                                         rc = LDAP_NO_MEMORY;
715                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
716                                         goto done;
717                                 }
718                                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
719                                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num *
720                                         sizeof(int) );
721                                 for ( i=0; i<si->si_syncCookie.numcsns; i++ )
722                                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
723                         }
724                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
725                 }
726
727                 ch_free( si->si_syncCookie.octet_str.bv_val );
728                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
729                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
730                         si->si_syncCookie.sid );
731         } else {
732                 /* ITS#6367: recreate the cookie so it has our SID, not our peer's */
733                 ch_free( si->si_syncCookie.octet_str.bv_val );
734                 BER_BVZERO( &si->si_syncCookie.octet_str );
735                 /* Look for contextCSN from syncprov overlay. */
736                 check_syncprov( op, si );
737                 if ( BER_BVISNULL( &si->si_syncCookie.octet_str ))
738                         slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
739                                 si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
740                                 si->si_syncCookie.sid );
741         }
742
743         si->si_refreshDone = 0;
744         si->si_refreshBeg = slap_get_time();
745         si->si_refreshCount = 0;
746         si->si_refreshTxn = NULL;
747         Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s starting refresh\n",
748                 si->si_ridtxt, 0, 0 );
749
750         rc = ldap_sync_search( si, op->o_tmpmemctx );
751
752         if( rc != LDAP_SUCCESS ) {
753                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s "
754                         "ldap_search_ext: %s (%d)\n",
755                         si->si_ridtxt, ldap_err2string( rc ), rc );
756         }
757
758 done:
759         if ( rc ) {
760                 if ( si->si_ld ) {
761                         ldap_unbind_ext( si->si_ld, NULL, NULL );
762                         si->si_ld = NULL;
763                 }
764         }
765
766         return rc;
767 }
768
769 static int
770 compare_csns( struct sync_cookie *sc1, struct sync_cookie *sc2, int *which )
771 {
772         int i, j, match = 0;
773         const char *text;
774
775         *which = 0;
776
777         if ( sc1->numcsns < sc2->numcsns ) {
778                 *which = sc1->numcsns;
779                 return -1;
780         }
781
782         for (j=0; j<sc2->numcsns; j++) {
783                 for (i=0; i<sc1->numcsns; i++) {
784                         if ( sc1->sids[i] != sc2->sids[j] )
785                                 continue;
786                         value_match( &match, slap_schema.si_ad_entryCSN,
787                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
788                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
789                                 &sc1->ctxcsn[i], &sc2->ctxcsn[j], &text );
790                         if ( match < 0 ) {
791                                 *which = j;
792                                 return match;
793                         }
794                         break;
795                 }
796                 if ( i == sc1->numcsns ) {
797                         /* sc2 has a sid sc1 lacks */
798                         *which = j;
799                         return -1;
800                 }
801         }
802         return match;
803 }
804
805 #define SYNC_PAUSED     -3
806
807 static int
808 do_syncrep2(
809         Operation *op,
810         syncinfo_t *si )
811 {
812         BerElementBuffer berbuf;
813         BerElement      *ber = (BerElement *)&berbuf;
814
815         LDAPMessage     *msg = NULL;
816
817         struct sync_cookie      syncCookie = { NULL };
818         struct sync_cookie      syncCookie_req = { NULL };
819
820         int             rc,
821                         err = LDAP_SUCCESS;
822
823         Modifications   *modlist = NULL;
824
825         int                             m;
826
827         struct timeval *tout_p = NULL;
828         struct timeval tout = { 0, 0 };
829
830         int             refreshDeletes = 0;
831         char empty[6] = "empty";
832
833         if ( slapd_shutdown ) {
834                 rc = -2;
835                 goto done;
836         }
837
838         ber_init2( ber, NULL, LBER_USE_DER );
839         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
840
841         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 %s\n", si->si_ridtxt, 0, 0 );
842
843         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
844
845         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST && si->si_refreshDone ) {
846                 tout_p = &tout;
847         } else {
848                 tout_p = NULL;
849         }
850
851         while ( ( rc = ldap_result( si->si_ld, si->si_msgid, LDAP_MSG_ONE,
852                 tout_p, &msg ) ) > 0 )
853         {
854                 int                             match, punlock, syncstate;
855                 struct berval   *retdata, syncUUID[2], cookie = BER_BVNULL;
856                 char                    *retoid;
857                 LDAPControl             **rctrls = NULL, *rctrlp = NULL;
858                 BerVarray               syncUUIDs;
859                 ber_len_t               len;
860                 ber_tag_t               si_tag;
861                 Entry                   *entry;
862                 struct berval   bdn;
863
864                 if ( slapd_shutdown ) {
865                         rc = -2;
866                         goto done;
867                 }
868                 switch( ldap_msgtype( msg ) ) {
869                 case LDAP_RES_SEARCH_ENTRY:
870                         ldap_get_entry_controls( si->si_ld, msg, &rctrls );
871                         ldap_get_dn_ber( si->si_ld, msg, NULL, &bdn );
872                         if (!bdn.bv_len) {
873                                 bdn.bv_val = empty;
874                                 bdn.bv_len = sizeof(empty)-1;
875                         }
876                         /* we can't work without the control */
877                         if ( rctrls ) {
878                                 LDAPControl **next = NULL;
879                                 /* NOTE: make sure we use the right one;
880                                  * a better approach would be to run thru
881                                  * the whole list and take care of all */
882                                 /* NOTE: since we issue the search request,
883                                  * we should know what controls to expect,
884                                  * and there should be none apart from the
885                                  * sync-related control */
886                                 rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_STATE, rctrls, &next );
887                                 if ( next && ldap_control_find( LDAP_CONTROL_SYNC_STATE, next, NULL ) )
888                                 {
889                                         bdn.bv_val[bdn.bv_len] = '\0';
890                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
891                                                 "got search entry with multiple "
892                                                 "Sync State control (%s)\n", si->si_ridtxt, bdn.bv_val, 0 );
893                                         ldap_controls_free( rctrls );
894                                         rc = -1;
895                                         goto done;
896                                 }
897                         }
898                         if ( rctrlp == NULL ) {
899                                 bdn.bv_val[bdn.bv_len] = '\0';
900                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
901                                         "got search entry without "
902                                         "Sync State control (%s)\n", si->si_ridtxt, bdn.bv_val, 0 );
903                                 rc = -1;
904                                 goto done;
905                         }
906                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
907                         if ( ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID[0] )
908                                         == LBER_ERROR ) {
909                                 bdn.bv_val[bdn.bv_len] = '\0';
910                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s malformed message (%s)\n",
911                                         si->si_ridtxt, bdn.bv_val, 0 );
912                                 ldap_controls_free( rctrls );
913                                 rc = -1;
914                                 goto done;
915                         }
916                         /* FIXME: what if syncUUID is NULL or empty?
917                          * (happens with back-sql...) */
918                         if ( syncUUID[0].bv_len != UUIDLEN ) {
919                                 bdn.bv_val[bdn.bv_len] = '\0';
920                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
921                                         "got empty or invalid syncUUID with LDAP_SYNC_%s (%s)\n",
922                                         si->si_ridtxt,
923                                         syncrepl_state2str( syncstate ), bdn.bv_val );
924                                 ldap_controls_free( rctrls );
925                                 rc = -1;
926                                 goto done;
927                         }
928                         punlock = -1;
929                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
930                                 if ( ber_scanf( ber, /*"{"*/ "m}", &cookie ) != LBER_ERROR ) {
931
932                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
933                                         si->si_ridtxt,
934                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
935
936                                 if ( !BER_BVISNULL( &cookie ) ) {
937                                         ch_free( syncCookie.octet_str.bv_val );
938                                         ber_dupbv( &syncCookie.octet_str, &cookie );
939                                 }
940                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
941                                 {
942                                         slap_parse_sync_cookie( &syncCookie, NULL );
943                                         if ( syncCookie.ctxcsn ) {
944                                                 int i, sid = slap_parse_csn_sid( syncCookie.ctxcsn );
945                                                 check_syncprov( op, si );
946                                                 ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
947                                                 for ( i =0; i<si->si_cookieState->cs_num; i++ ) {
948 #ifdef CHATTY_SYNCLOG
949                                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN for sid %d: %s\n",
950                                                                 si->si_ridtxt, i, si->si_cookieState->cs_vals[i].bv_val );
951 #endif
952                                                         /* new SID */
953                                                         if ( sid < si->si_cookieState->cs_sids[i] )
954                                                                 break;
955                                                         if ( si->si_cookieState->cs_sids[i] == sid ) {
956                                                                 if ( ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_vals[i] ) <= 0 ) {
957                                                                         bdn.bv_val[bdn.bv_len] = '\0';
958                                                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN too old, ignoring %s (%s)\n",
959                                                                                 si->si_ridtxt, syncCookie.ctxcsn->bv_val, bdn.bv_val );
960                                                                         si->si_too_old = 1;
961                                                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
962                                                                         ldap_controls_free( rctrls );
963                                                                         rc = 0;
964                                                                         goto done;
965                                                                 }
966                                                                 si->si_too_old = 0;
967                                                                 break;
968                                                         }
969                                                 }
970                                                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
971
972                                                 /* check pending CSNs too */
973                                                 while ( ldap_pvt_thread_mutex_trylock( &si->si_cookieState->cs_pmutex )) {
974                                                         if ( slapd_shutdown ) {
975                                                                 rc = -2;
976                                                                 goto done;
977                                                         }
978                                                         if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
979                                                                 ldap_pvt_thread_yield();
980                                                 }
981
982                                                 for ( i =0; i<si->si_cookieState->cs_pnum; i++ ) {
983                                                         if ( sid < si->si_cookieState->cs_psids[i] )
984                                                                 break;
985                                                         if ( si->si_cookieState->cs_psids[i] == sid ) {
986                                                                 if ( ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_pvals[i] ) <= 0 ) {
987                                                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_pmutex );
988                                                                         bdn.bv_val[bdn.bv_len] = '\0';
989                                                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN pending, ignoring %s (%s)\n",
990                                                                                 si->si_ridtxt, syncCookie.ctxcsn->bv_val, bdn.bv_val );
991                                                                         ldap_controls_free( rctrls );
992                                                                         rc = 0;
993                                                                         goto done;
994                                                                 }
995                                                                 ber_bvreplace( &si->si_cookieState->cs_pvals[i],
996                                                                         syncCookie.ctxcsn );
997                                                                 break;
998                                                         }
999                                                 }
1000                                                 /* new SID, add it */
1001                                                 if ( i == si->si_cookieState->cs_pnum ||
1002                                                         sid != si->si_cookieState->cs_psids[i] ) {
1003                                                         slap_insert_csn_sids(
1004                                                                 (struct sync_cookie *)&si->si_cookieState->cs_pvals,
1005                                                                 i, sid, syncCookie.ctxcsn );
1006                                                 }
1007                                                 assert( punlock < 0 );
1008                                                 punlock = i;
1009                                         } else if (si->si_too_old) {
1010                                                 bdn.bv_val[bdn.bv_len] = '\0';
1011                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN too old, ignoring (%s)\n",
1012                                                         si->si_ridtxt, bdn.bv_val, 0 );
1013                                                 ldap_controls_free( rctrls );
1014                                                 rc = 0;
1015                                                 goto done;
1016                                         }
1017                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1018                                 }
1019                                 }
1020                         }
1021                         rc = 0;
1022                         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
1023                                 modlist = NULL;
1024                                 if ( ( rc = syncrepl_message_to_op( si, op, msg ) ) == LDAP_SUCCESS &&
1025                                         syncCookie.ctxcsn )
1026                                 {
1027                                         rc = syncrepl_updateCookie( si, op, &syncCookie );
1028                                 } else switch ( rc ) {
1029                                         case LDAP_ALREADY_EXISTS:
1030                                         case LDAP_NO_SUCH_OBJECT:
1031                                         case LDAP_NO_SUCH_ATTRIBUTE:
1032                                         case LDAP_TYPE_OR_VALUE_EXISTS:
1033                                         case LDAP_NOT_ALLOWED_ON_NONLEAF:
1034                                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
1035                                                 si->si_logstate = SYNCLOG_FALLBACK;
1036                                                 ldap_abandon_ext( si->si_ld, si->si_msgid, NULL, NULL );
1037                                                 bdn.bv_val[bdn.bv_len] = '\0';
1038                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s delta-sync lost sync on (%s), switching to REFRESH\n",
1039                                                         si->si_ridtxt, bdn.bv_val, 0 );
1040                                                 if (si->si_strict_refresh) {
1041                                                         slap_suspend_listeners();
1042                                                         connections_drop();
1043                                                 }
1044                                                 break;
1045                                         default:
1046                                                 break;
1047                                 }
1048                         } else if ( ( rc = syncrepl_message_to_entry( si, op, msg,
1049                                 &modlist, &entry, syncstate, syncUUID ) ) == LDAP_SUCCESS )
1050                         {
1051                                 if ( ( rc = syncrepl_entry( si, op, entry, &modlist,
1052                                         syncstate, syncUUID, syncCookie.ctxcsn ) ) == LDAP_SUCCESS &&
1053                                         syncCookie.ctxcsn )
1054                                 {
1055                                         rc = syncrepl_updateCookie( si, op, &syncCookie );
1056                                 }
1057                         }
1058                         if ( punlock >= 0 ) {
1059                                 /* on failure, revert pending CSN */
1060                                 if ( rc != LDAP_SUCCESS ) {
1061                                         int i;
1062                                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
1063                                         for ( i = 0; i<si->si_cookieState->cs_num; i++ ) {
1064                                                 if ( si->si_cookieState->cs_sids[i] == si->si_cookieState->cs_psids[punlock] ) {
1065                                                         ber_bvreplace( &si->si_cookieState->cs_pvals[punlock],
1066                                                                 &si->si_cookieState->cs_vals[i] );
1067                                                         break;
1068                                                 }
1069                                         }
1070                                         if ( i == si->si_cookieState->cs_num )
1071                                                 si->si_cookieState->cs_pvals[punlock].bv_val[0] = '\0';
1072                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
1073                                 }
1074                                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_pmutex );
1075                         }
1076                         ldap_controls_free( rctrls );
1077                         if ( modlist ) {
1078                                 slap_mods_free( modlist, 1 );
1079                         }
1080                         if ( rc )
1081                                 goto done;
1082                         break;
1083
1084                 case LDAP_RES_SEARCH_REFERENCE:
1085                         Debug( LDAP_DEBUG_ANY,
1086                                 "do_syncrep2: %s reference received error\n",
1087                                 si->si_ridtxt, 0, 0 );
1088                         break;
1089
1090                 case LDAP_RES_SEARCH_RESULT:
1091                         Debug( LDAP_DEBUG_SYNC,
1092                                 "do_syncrep2: %s LDAP_RES_SEARCH_RESULT\n",
1093                                 si->si_ridtxt, 0, 0 );
1094                         err = LDAP_OTHER; /* FIXME check parse result properly */
1095                         ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
1096                                 &rctrls, 0 );
1097 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
1098                         if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
1099                                 /* map old result code to registered code */
1100                                 err = LDAP_SYNC_REFRESH_REQUIRED;
1101                         }
1102 #endif
1103                         if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
1104                                 if ( si->si_logstate == SYNCLOG_LOGGING ) {
1105                                         si->si_logstate = SYNCLOG_FALLBACK;
1106                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s delta-sync lost sync, switching to REFRESH\n",
1107                                                 si->si_ridtxt, 0, 0 );
1108                                         if (si->si_strict_refresh) {
1109                                                 slap_suspend_listeners();
1110                                                 connections_drop();
1111                                         }
1112                                 }
1113                                 rc = err;
1114                                 goto done;
1115                         }
1116                         if ( err ) {
1117                                 Debug( LDAP_DEBUG_ANY,
1118                                         "do_syncrep2: %s LDAP_RES_SEARCH_RESULT (%d) %s\n",
1119                                         si->si_ridtxt, err, ldap_err2string( err ) );
1120                         }
1121                         if ( rctrls ) {
1122                                 LDAPControl **next = NULL;
1123                                 /* NOTE: make sure we use the right one;
1124                                  * a better approach would be to run thru
1125                                  * the whole list and take care of all */
1126                                 /* NOTE: since we issue the search request,
1127                                  * we should know what controls to expect,
1128                                  * and there should be none apart from the
1129                                  * sync-related control */
1130                                 rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_DONE, rctrls, &next );
1131                                 if ( next && ldap_control_find( LDAP_CONTROL_SYNC_DONE, next, NULL ) )
1132                                 {
1133                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1134                                                 "got search result with multiple "
1135                                                 "Sync State control\n", si->si_ridtxt, 0, 0 );
1136                                         ldap_controls_free( rctrls );
1137                                         rc = -1;
1138                                         goto done;
1139                                 }
1140                         }
1141                         if ( rctrlp ) {
1142                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
1143
1144                                 ber_scanf( ber, "{" /*"}"*/);
1145                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
1146                                         ber_scanf( ber, "m", &cookie );
1147
1148                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1149                                                 si->si_ridtxt, 
1150                                                 BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1151
1152                                         if ( !BER_BVISNULL( &cookie ) ) {
1153                                                 ch_free( syncCookie.octet_str.bv_val );
1154                                                 ber_dupbv( &syncCookie.octet_str, &cookie);
1155                                         }
1156                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1157                                         {
1158                                                 slap_parse_sync_cookie( &syncCookie, NULL );
1159                                                 op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1160                                         }
1161                                 }
1162                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
1163                                 {
1164                                         ber_scanf( ber, "b", &refreshDeletes );
1165                                 }
1166                                 ber_scanf( ber, /*"{"*/ "}" );
1167                         }
1168                         if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1169                                 slap_sync_cookie_free( &syncCookie_req, 0 );
1170                                 slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1171                         }
1172                         if ( !syncCookie.ctxcsn ) {
1173                                 match = 1;
1174                         } else if ( !syncCookie_req.ctxcsn ) {
1175                                 match = -1;
1176                                 m = 0;
1177                         } else {
1178                                 match = compare_csns( &syncCookie_req, &syncCookie, &m );
1179                         }
1180                         if ( rctrls ) {
1181                                 ldap_controls_free( rctrls );
1182                         }
1183                         if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
1184                                 /* FIXME : different error behaviors according to
1185                                  *      1) err code : LDAP_BUSY ...
1186                                  *      2) on err policy : stop service, stop sync, retry
1187                                  */
1188                                 if ( refreshDeletes == 0 && match < 0 &&
1189                                         err == LDAP_SUCCESS &&
1190                                         syncCookie_req.numcsns == syncCookie.numcsns )
1191                                 {
1192                                         syncrepl_del_nonpresent( op, si, NULL,
1193                                                 &syncCookie, m );
1194                                 } else if ( si->si_presentlist ) {
1195                                         presentlist_free( si->si_presentlist );
1196                                         si->si_presentlist = NULL;
1197                                 }
1198                         }
1199                         if ( syncCookie.ctxcsn && match < 0 && err == LDAP_SUCCESS )
1200                         {
1201                                 rc = syncrepl_updateCookie( si, op, &syncCookie );
1202                         }
1203                         if ( si->si_refreshCount ) {
1204                                 LDAP_SLIST_REMOVE( &op->o_extra, si->si_refreshTxn, OpExtra, oe_next );
1205                                 op->o_bd->bd_info->bi_op_txn( op, SLAP_TXN_COMMIT, &si->si_refreshTxn );
1206                                 si->si_refreshCount = 0;
1207                                 si->si_refreshTxn = NULL;
1208                         }
1209                         si->si_refreshEnd = slap_get_time();
1210                         if ( err == LDAP_SUCCESS
1211                                 && si->si_logstate == SYNCLOG_FALLBACK ) {
1212                                 si->si_logstate = SYNCLOG_LOGGING;
1213                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
1214                                 slap_resume_listeners();
1215                         } else {
1216                                 rc = -2;
1217                         }
1218                         goto done;
1219
1220                 case LDAP_RES_INTERMEDIATE:
1221                         retoid = NULL;
1222                         retdata = NULL;
1223                         rc = ldap_parse_intermediate( si->si_ld, msg,
1224                                 &retoid, &retdata, NULL, 0 );
1225                         if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
1226                                 ber_init2( ber, retdata, LBER_USE_DER );
1227
1228                                 switch ( si_tag = ber_peek_tag( ber, &len ) ) {
1229                                 ber_tag_t tag;
1230                                 case LDAP_TAG_SYNC_NEW_COOKIE:
1231                                         Debug( LDAP_DEBUG_SYNC,
1232                                                 "do_syncrep2: %s %s - %s\n", 
1233                                                 si->si_ridtxt,
1234                                                 "LDAP_RES_INTERMEDIATE", 
1235                                                 "NEW_COOKIE" );
1236                                         ber_scanf( ber, "tm", &tag, &cookie );
1237                                         Debug( LDAP_DEBUG_SYNC,
1238                                                 "do_syncrep2: %s NEW_COOKIE: %s\n",
1239                                                 si->si_ridtxt,
1240                                                 cookie.bv_val, 0);
1241                                         if ( !BER_BVISNULL( &cookie ) ) {
1242                                                 ch_free( syncCookie.octet_str.bv_val );
1243                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
1244                                         }
1245                                         if (!BER_BVISNULL( &syncCookie.octet_str ) ) {
1246                                                 slap_parse_sync_cookie( &syncCookie, NULL );
1247                                                 op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1248                                         }
1249                                         break;
1250                                 case LDAP_TAG_SYNC_REFRESH_DELETE:
1251                                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
1252                                         Debug( LDAP_DEBUG_SYNC,
1253                                                 "do_syncrep2: %s %s - %s\n", 
1254                                                 si->si_ridtxt,
1255                                                 "LDAP_RES_INTERMEDIATE", 
1256                                                 si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
1257                                                 "REFRESH_PRESENT" : "REFRESH_DELETE" );
1258                                         if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
1259                                                 si->si_refreshDelete = 1;
1260                                         } else {
1261                                                 si->si_refreshPresent = 1;
1262                                         }
1263                                         ber_scanf( ber, "t{" /*"}"*/, &tag );
1264                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
1265                                         {
1266                                                 ber_scanf( ber, "m", &cookie );
1267
1268                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1269                                                         si->si_ridtxt, 
1270                                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1271
1272                                                 if ( !BER_BVISNULL( &cookie ) ) {
1273                                                         ch_free( syncCookie.octet_str.bv_val );
1274                                                         ber_dupbv( &syncCookie.octet_str, &cookie );
1275                                                 }
1276                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1277                                                 {
1278                                                         slap_parse_sync_cookie( &syncCookie, NULL );
1279                                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1280                                                 }
1281                                         }
1282                                         /* Defaults to TRUE */
1283                                         if ( ber_peek_tag( ber, &len ) ==
1284                                                 LDAP_TAG_REFRESHDONE )
1285                                         {
1286                                                 ber_scanf( ber, "b", &si->si_refreshDone );
1287                                         } else
1288                                         {
1289                                                 si->si_refreshDone = 1;
1290                                         }
1291                                         if ( si->si_refreshDone ) {
1292                                                 if ( si->si_refreshCount ) {
1293                                                         LDAP_SLIST_REMOVE( &op->o_extra, si->si_refreshTxn, OpExtra, oe_next );
1294                                                         op->o_bd->bd_info->bi_op_txn( op, SLAP_TXN_COMMIT, &si->si_refreshTxn );
1295                                                         si->si_refreshCount = 0;
1296                                                         si->si_refreshTxn = NULL;
1297                                                 }
1298                                                 si->si_refreshEnd = slap_get_time();
1299         Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s finished refresh\n",
1300                 si->si_ridtxt, 0, 0 );
1301                                         }
1302                                         ber_scanf( ber, /*"{"*/ "}" );
1303                                         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST &&
1304                                                 si->si_refreshDone )
1305                                                 tout_p = &tout;
1306                                         break;
1307                                 case LDAP_TAG_SYNC_ID_SET:
1308                                         Debug( LDAP_DEBUG_SYNC,
1309                                                 "do_syncrep2: %s %s - %s\n", 
1310                                                 si->si_ridtxt,
1311                                                 "LDAP_RES_INTERMEDIATE", 
1312                                                 "SYNC_ID_SET" );
1313                                         ber_scanf( ber, "t{" /*"}"*/, &tag );
1314                                         if ( ber_peek_tag( ber, &len ) ==
1315                                                 LDAP_TAG_SYNC_COOKIE )
1316                                         {
1317                                                 ber_scanf( ber, "m", &cookie );
1318
1319                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1320                                                         si->si_ridtxt,
1321                                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1322
1323                                                 if ( !BER_BVISNULL( &cookie ) ) {
1324                                                         ch_free( syncCookie.octet_str.bv_val );
1325                                                         ber_dupbv( &syncCookie.octet_str, &cookie );
1326                                                 }
1327                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1328                                                 {
1329                                                         slap_parse_sync_cookie( &syncCookie, NULL );
1330                                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1331                                                         compare_csns( &syncCookie_req, &syncCookie, &m );
1332                                                 }
1333                                         }
1334                                         if ( ber_peek_tag( ber, &len ) ==
1335                                                 LDAP_TAG_REFRESHDELETES )
1336                                         {
1337                                                 ber_scanf( ber, "b", &refreshDeletes );
1338                                         }
1339                                         syncUUIDs = NULL;
1340                                         rc = ber_scanf( ber, "[W]", &syncUUIDs );
1341                                         ber_scanf( ber, /*"{"*/ "}" );
1342                                         if ( rc != LBER_ERROR ) {
1343                                                 if ( refreshDeletes ) {
1344                                                         syncrepl_del_nonpresent( op, si, syncUUIDs,
1345                                                                 &syncCookie, m );
1346                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
1347                                                 } else {
1348                                                         int i;
1349                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
1350                                                                 (void)presentlist_insert( si, &syncUUIDs[i] );
1351                                                                 slap_sl_free( syncUUIDs[i].bv_val, op->o_tmpmemctx );
1352                                                         }
1353                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
1354                                                 }
1355                                         }
1356                                         rc = 0;
1357                                         slap_sync_cookie_free( &syncCookie, 0 );
1358                                         break;
1359                                 default:
1360                                         Debug( LDAP_DEBUG_ANY,
1361                                                 "do_syncrep2: %s unknown syncinfo tag (%ld)\n",
1362                                                 si->si_ridtxt, (long) si_tag, 0 );
1363                                         ldap_memfree( retoid );
1364                                         ber_bvfree( retdata );
1365                                         continue;
1366                                 }
1367
1368                                 if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1369                                         slap_sync_cookie_free( &syncCookie_req, 0 );
1370                                         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1371                                 }
1372                                 if ( !syncCookie.ctxcsn ) {
1373                                         match = 1;
1374                                 } else if ( !syncCookie_req.ctxcsn ) {
1375                                         match = -1;
1376                                         m = 0;
1377                                 } else {
1378                                         match = compare_csns( &syncCookie_req, &syncCookie, &m );
1379                                 }
1380
1381                                 if ( match < 0 ) {
1382                                         if ( si->si_refreshPresent == 1 &&
1383                                                 si_tag != LDAP_TAG_SYNC_NEW_COOKIE &&
1384                                                 syncCookie_req.numcsns == syncCookie.numcsns ) {
1385                                                 syncrepl_del_nonpresent( op, si, NULL,
1386                                                         &syncCookie, m );
1387                                         }
1388
1389                                         if ( syncCookie.ctxcsn )
1390                                         {
1391                                                 rc = syncrepl_updateCookie( si, op, &syncCookie);
1392                                         }
1393                                         if ( si->si_presentlist ) {
1394                                                 presentlist_free( si->si_presentlist );
1395                                                 si->si_presentlist = NULL;
1396                                         }
1397                                 } 
1398
1399                                 ldap_memfree( retoid );
1400                                 ber_bvfree( retdata );
1401
1402                                 if ( rc )
1403                                         goto done;
1404
1405                         } else {
1406                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1407                                         "unknown intermediate response (%d)\n",
1408                                         si->si_ridtxt, rc, 0 );
1409                                 ldap_memfree( retoid );
1410                                 ber_bvfree( retdata );
1411                         }
1412                         break;
1413
1414                 default:
1415                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1416                                 "unknown message (0x%02lx)\n",
1417                                 si->si_ridtxt,
1418                                 (unsigned long)ldap_msgtype( msg ), 0 );
1419                         break;
1420
1421                 }
1422                 if ( !BER_BVISNULL( &syncCookie.octet_str ) ) {
1423                         slap_sync_cookie_free( &syncCookie_req, 0 );
1424                         syncCookie_req = syncCookie;
1425                         memset( &syncCookie, 0, sizeof( syncCookie ));
1426                 }
1427                 ldap_msgfree( msg );
1428                 msg = NULL;
1429                 if ( ldap_pvt_thread_pool_pausing( &connection_pool )) {
1430                         slap_sync_cookie_free( &syncCookie, 0 );
1431                         slap_sync_cookie_free( &syncCookie_req, 0 );
1432                         if ( si->si_refreshCount ) {
1433                                 LDAP_SLIST_REMOVE( &op->o_extra, si->si_refreshTxn, OpExtra, oe_next );
1434                                 op->o_bd->bd_info->bi_op_txn( op, SLAP_TXN_COMMIT, &si->si_refreshTxn );
1435                                 si->si_refreshCount = 0;
1436                                 si->si_refreshTxn = NULL;
1437                         }
1438                         return SYNC_PAUSED;
1439                 }
1440         }
1441
1442         if ( rc == -1 ) {
1443                 rc = LDAP_OTHER;
1444                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1445                 err = rc;
1446         }
1447
1448 done:
1449         if ( err != LDAP_SUCCESS ) {
1450                 Debug( LDAP_DEBUG_ANY,
1451                         "do_syncrep2: %s (%d) %s\n",
1452                         si->si_ridtxt, err, ldap_err2string( err ) );
1453         }
1454
1455         slap_sync_cookie_free( &syncCookie, 0 );
1456         slap_sync_cookie_free( &syncCookie_req, 0 );
1457
1458         if ( msg ) ldap_msgfree( msg );
1459
1460         if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
1461                 if ( si->si_conn ) {
1462                         connection_client_stop( si->si_conn );
1463                         si->si_conn = NULL;
1464                 }
1465                 ldap_unbind_ext( si->si_ld, NULL, NULL );
1466                 si->si_ld = NULL;
1467         }
1468
1469         return rc;
1470 }
1471
1472 static void *
1473 do_syncrepl(
1474         void    *ctx,
1475         void    *arg )
1476 {
1477         struct re_s* rtask = arg;
1478         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1479         Connection conn = {0};
1480         OperationBuffer opbuf;
1481         Operation *op;
1482         int rc = LDAP_SUCCESS;
1483         int dostop = 0;
1484         ber_socket_t s;
1485         int i, defer = 1, fail = 0, freeinfo = 0;
1486         Backend *be;
1487
1488         if ( si == NULL )
1489                 return NULL;
1490         if ( slapd_shutdown )
1491                 return NULL;
1492
1493         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl %s\n", si->si_ridtxt, 0, 0 );
1494
1495         /* Don't get stuck here while a pause is initiated */
1496         while ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
1497                 if ( slapd_shutdown )
1498                         return NULL;
1499                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1500                         ldap_pvt_thread_yield();
1501         }
1502
1503         si->si_too_old = 0;
1504
1505         if ( si->si_ctype < 1 ) {
1506                 goto deleted;
1507         }
1508
1509         switch( abs( si->si_type ) ) {
1510         case LDAP_SYNC_REFRESH_ONLY:
1511         case LDAP_SYNC_REFRESH_AND_PERSIST:
1512                 break;
1513         default:
1514                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1515                 return NULL;
1516         }
1517
1518         if ( slapd_shutdown ) {
1519                 if ( si->si_ld ) {
1520                         if ( si->si_conn ) {
1521                                 connection_client_stop( si->si_conn );
1522                                 si->si_conn = NULL;
1523                         }
1524                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1525                         si->si_ld = NULL;
1526                 }
1527                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1528                 return NULL;
1529         }
1530
1531         connection_fake_init( &conn, &opbuf, ctx );
1532         op = &opbuf.ob_op;
1533         /* o_connids must be unique for slap_graduate_commit_csn */
1534         op->o_connid = SLAPD_SYNC_RID2SYNCCONN(si->si_rid);
1535
1536         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1537         be = si->si_be;
1538
1539         /* Coordinate contextCSN updates with any syncprov overlays
1540          * in use. This may be complicated by the use of the glue
1541          * overlay.
1542          *
1543          * Typically there is a single syncprov mastering the entire
1544          * glued tree. In that case, our contextCSN updates should
1545          * go to the master DB. But if there is no syncprov on the
1546          * master DB, then nothing special is needed here.
1547          *
1548          * Alternatively, there may be individual syncprov overlays
1549          * on each glued branch. In that case, each syncprov only
1550          * knows about changes within its own branch. And so our
1551          * contextCSN updates should only go to the local DB.
1552          */
1553         if ( !si->si_wbe ) {
1554                 if ( SLAP_GLUE_SUBORDINATE( be ) && !overlay_is_inst( be, "syncprov" )) {
1555                         BackendDB * top_be = select_backend( &be->be_nsuffix[0], 1 );
1556                         if ( overlay_is_inst( top_be, "syncprov" ))
1557                                 si->si_wbe = top_be;
1558                         else
1559                                 si->si_wbe = be;
1560                 } else {
1561                         si->si_wbe = be;
1562                 }
1563                 if ( SLAP_SYNC_SUBENTRY( si->si_wbe )) {
1564                         build_new_dn( &si->si_contextdn, &si->si_wbe->be_nsuffix[0],
1565                                 (struct berval *)&slap_ldapsync_cn_bv, NULL );
1566                 } else {
1567                         si->si_contextdn = si->si_wbe->be_nsuffix[0];
1568                 }
1569         }
1570         if ( !si->si_schemachecking )
1571                 op->o_no_schema_check = 1;
1572
1573         /* Establish session, do search */
1574         if ( !si->si_ld ) {
1575                 si->si_refreshDelete = 0;
1576                 si->si_refreshPresent = 0;
1577
1578                 if ( si->si_presentlist ) {
1579                     presentlist_free( si->si_presentlist );
1580                     si->si_presentlist = NULL;
1581                 }
1582
1583                 /* use main DB when retrieving contextCSN */
1584                 op->o_bd = si->si_wbe;
1585                 op->o_dn = op->o_bd->be_rootdn;
1586                 op->o_ndn = op->o_bd->be_rootndn;
1587                 rc = do_syncrep1( op, si );
1588         }
1589
1590 reload:
1591         /* Process results */
1592         if ( rc == LDAP_SUCCESS ) {
1593                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1594
1595                 /* use current DB */
1596                 op->o_bd = be;
1597                 op->o_dn = op->o_bd->be_rootdn;
1598                 op->o_ndn = op->o_bd->be_rootndn;
1599                 rc = do_syncrep2( op, si );
1600                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1601                         if ( BER_BVISNULL( &si->si_syncCookie.octet_str ))
1602                                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
1603                                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
1604                                         si->si_syncCookie.sid );
1605                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1606                         goto reload;
1607                 }
1608
1609 deleted:
1610                 /* We got deleted while running on cn=config */
1611                 if ( si->si_ctype < 1 ) {
1612                         if ( si->si_ctype == -1 ) {
1613                                 si->si_ctype = 0;
1614                                 freeinfo = 1;
1615                         }
1616                         if ( si->si_conn )
1617                                 dostop = 1;
1618                         rc = -1;
1619                 }
1620
1621                 if ( rc != SYNC_PAUSED ) {
1622                         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1623                                 /* If we succeeded, enable the connection for further listening.
1624                                  * If we failed, tear down the connection and reschedule.
1625                                  */
1626                                 if ( rc == LDAP_SUCCESS ) {
1627                                         if ( si->si_conn ) {
1628                                                 connection_client_enable( si->si_conn );
1629                                         } else {
1630                                                 si->si_conn = connection_client_setup( s, do_syncrepl, arg );
1631                                         } 
1632                                 } else if ( si->si_conn ) {
1633                                         dostop = 1;
1634                                 }
1635                         } else {
1636                                 if ( rc == -2 ) rc = 0;
1637                         }
1638                 }
1639         }
1640
1641         /* At this point, we have 5 cases:
1642          * 1) for any hard failure, give up and remove this task
1643          * 2) for ServerDown, reschedule this task to run later
1644          * 3) for threadpool pause, reschedule to run immediately
1645          * 4) for Refresh and Success, reschedule to run
1646          * 5) for Persist and Success, reschedule to defer
1647          */
1648         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1649
1650         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask ) ) {
1651                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1652         }
1653
1654         if ( dostop ) {
1655                 connection_client_stop( si->si_conn );
1656                 si->si_conn = NULL;
1657         }
1658
1659         if ( rc == SYNC_PAUSED ) {
1660                 rtask->interval.tv_sec = 0;
1661                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1662                 rtask->interval.tv_sec = si->si_interval;
1663                 rc = 0;
1664         } else if ( rc == LDAP_SUCCESS ) {
1665                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1666                         defer = 0;
1667                 }
1668                 rtask->interval.tv_sec = si->si_interval;
1669                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1670                 if ( si->si_retrynum ) {
1671                         for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1672                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1673                         }
1674                         si->si_retrynum[i] = RETRYNUM_TAIL;
1675                 }
1676         } else {
1677                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1678                         if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1679                                 break;
1680                 }
1681
1682                 if ( si->si_ctype < 1
1683                         || !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1684                         if ( si->si_re ) {
1685                                 ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1686                                 si->si_re = NULL;
1687                         }
1688                         fail = RETRYNUM_TAIL;
1689                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1690                         if ( si->si_retrynum[i] > 0 )
1691                                 si->si_retrynum[i]--;
1692                         fail = si->si_retrynum[i];
1693                         rtask->interval.tv_sec = si->si_retryinterval[i];
1694                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1695                         slap_wake_listener();
1696                 }
1697         }
1698
1699         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1700         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1701
1702         if ( rc ) {
1703                 if ( fail == RETRYNUM_TAIL ) {
1704                         Debug( LDAP_DEBUG_ANY,
1705                                 "do_syncrepl: %s rc %d quitting\n",
1706                                 si->si_ridtxt, rc, 0 );
1707                 } else if ( fail > 0 ) {
1708                         Debug( LDAP_DEBUG_ANY,
1709                                 "do_syncrepl: %s rc %d retrying (%d retries left)\n",
1710                                 si->si_ridtxt, rc, fail );
1711                 } else {
1712                         Debug( LDAP_DEBUG_ANY,
1713                                 "do_syncrepl: %s rc %d retrying\n",
1714                                 si->si_ridtxt, rc, 0 );
1715                 }
1716         }
1717
1718         /* Do final delete cleanup */
1719         if ( freeinfo ) {
1720                 syncinfo_free( si, 0 );
1721         }
1722         return NULL;
1723 }
1724
1725 #ifdef ENABLE_REWRITE
1726 static int
1727 syncrepl_rewrite_dn(
1728         syncinfo_t *si,
1729         struct berval *dn,
1730         struct berval *sdn )
1731 {
1732         char nul;
1733         int rc;
1734
1735         nul = dn->bv_val[dn->bv_len];
1736         dn->bv_val[dn->bv_len] = 0;
1737         rc = rewrite( si->si_rewrite, SUFFIXM_CTX, dn->bv_val, &sdn->bv_val );
1738         dn->bv_val[dn->bv_len] = nul;
1739
1740         if ( sdn->bv_val == dn->bv_val )
1741                 sdn->bv_val = NULL;
1742         else if ( rc == REWRITE_REGEXEC_OK && sdn->bv_val )
1743                 sdn->bv_len = strlen( sdn->bv_val );
1744         return rc;
1745 }
1746 #define REWRITE_VAL(si, ad, bv, bv2)    \
1747         BER_BVZERO( &bv2 );     \
1748         if ( si->si_rewrite && ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName) \
1749                 syncrepl_rewrite_dn( si, &bv, &bv2); \
1750         if ( BER_BVISNULL( &bv2 ))  \
1751                 ber_dupbv( &bv2, &bv )
1752 #define REWRITE_DN(si, bv, bv2, dn, ndn) \
1753         BER_BVZERO( &bv2 );     \
1754         if (si->si_rewrite) \
1755                 syncrepl_rewrite_dn(si, &bv, &bv2); \
1756         rc = dnPrettyNormal( NULL, bv2.bv_val ? &bv2 : &bv, &dn, &ndn, op->o_tmpmemctx ); \
1757         ch_free(bv2.bv_val)
1758 #else
1759 #define REWRITE_VAL(si, ad, bv, bv2)    ber_dupbv(&bv2, &bv)
1760 #define REWRITE_DN(si, bv, bv2, dn, ndn) \
1761         rc = dnPrettyNormal( NULL, &bv, &dn, &ndn, op->o_tmpmemctx )
1762 #endif
1763
1764
1765 static slap_verbmasks modops[] = {
1766         { BER_BVC("add"), LDAP_REQ_ADD },
1767         { BER_BVC("delete"), LDAP_REQ_DELETE },
1768         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1769         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1770         { BER_BVNULL, 0 }
1771 };
1772
1773 static int
1774 syncrepl_accesslog_mods(
1775         syncinfo_t *si,
1776         struct berval *vals,
1777         struct Modifications **modres
1778 )
1779 {
1780         char *colon;
1781         const char *text;
1782         AttributeDescription *ad;
1783         struct berval bv, bv2;
1784         short op;
1785         Modifications *mod = NULL, *modlist = NULL, **modtail;
1786         int i, rc = 0;
1787
1788         modtail = &modlist;
1789
1790         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1791                 ad = NULL;
1792                 bv = vals[i];
1793
1794                 colon = ber_bvchr( &bv, ':' );
1795                 if ( !colon ) {
1796                         /* Invalid */
1797                         continue;
1798                 }
1799
1800                 bv.bv_len = colon - bv.bv_val;
1801                 if ( slap_bv2ad( &bv, &ad, &text ) ) {
1802                         /* Invalid */
1803                         Debug( LDAP_DEBUG_ANY, "syncrepl_accesslog_mods: %s "
1804                                 "Invalid attribute %s, %s\n",
1805                                 si->si_ridtxt, bv.bv_val, text );
1806                         slap_mods_free( modlist, 1 );
1807                         modlist = NULL;
1808                         rc = -1;
1809                         break;
1810                 }
1811
1812                 /* Ignore dynamically generated attrs */
1813                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1814                         continue;
1815                 }
1816
1817                 /* Ignore excluded attrs */
1818                 if ( ldap_charray_inlist( si->si_exattrs,
1819                         ad->ad_type->sat_cname.bv_val ) )
1820                 {
1821                         continue;
1822                 }
1823
1824                 switch(colon[1]) {
1825                 case '+':       op = LDAP_MOD_ADD; break;
1826                 case '-':       op = LDAP_MOD_DELETE; break;
1827                 case '=':       op = LDAP_MOD_REPLACE; break;
1828                 case '#':       op = LDAP_MOD_INCREMENT; break;
1829                 default:        continue;
1830                 }
1831
1832                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1833                         mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1834                         mod->sml_flags = 0;
1835                         mod->sml_op = op;
1836                         mod->sml_next = NULL;
1837                         mod->sml_desc = ad;
1838                         mod->sml_type = ad->ad_cname;
1839                         mod->sml_values = NULL;
1840                         mod->sml_nvalues = NULL;
1841                         mod->sml_numvals = 0;
1842
1843                         *modtail = mod;
1844                         modtail = &mod->sml_next;
1845                 }
1846                 if ( colon[2] == ' ' ) {
1847                         bv.bv_val = colon + 3;
1848                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1849                         REWRITE_VAL( si, ad, bv, bv2 );
1850                         ber_bvarray_add( &mod->sml_values, &bv2 );
1851                         mod->sml_numvals++;
1852                 }
1853         }
1854         *modres = modlist;
1855         return rc;
1856 }
1857
1858 static int
1859 syncrepl_changelog_mods(
1860         syncinfo_t *si,
1861         struct berval *vals,
1862         struct Modifications **modres
1863 )
1864 {
1865         return -1;      /* FIXME */
1866 }
1867
1868 typedef struct OpExtraSync {
1869         OpExtra oe;
1870         syncinfo_t *oe_si;
1871 } OpExtraSync;
1872
1873 /* Copy the original modlist, split Replace ops into Delete/Add,
1874  * and drop mod opattrs since this modification is in the past.
1875  */
1876 static Modifications *mods_dup( Operation *op, Modifications *modlist, int match )
1877 {
1878         Modifications *mod, *modnew = NULL, *modtail = NULL;
1879         int size;
1880         for ( ; modlist; modlist = modlist->sml_next ) {
1881                 /* older ops */
1882                 if ( match < 0 ) {
1883                         if ( modlist->sml_desc == slap_schema.si_ad_modifiersName ||
1884                                 modlist->sml_desc == slap_schema.si_ad_modifyTimestamp ||
1885                                 modlist->sml_desc == slap_schema.si_ad_entryCSN )
1886                                 continue;
1887                         if ( modlist->sml_op == LDAP_MOD_REPLACE ) {
1888                                 mod = op->o_tmpalloc( sizeof(Modifications), op->o_tmpmemctx );
1889                                 mod->sml_desc = modlist->sml_desc;
1890                                 mod->sml_values = NULL;
1891                                 mod->sml_nvalues = NULL;
1892                                 mod->sml_op = LDAP_MOD_DELETE;
1893                                 mod->sml_numvals = 0;
1894                                 mod->sml_flags = 0;
1895                                 if ( !modnew )
1896                                         modnew = mod;
1897                                 if ( modtail )
1898                                         modtail->sml_next = mod;
1899                                 modtail = mod;
1900                         }
1901                 }
1902                 if ( modlist->sml_numvals ) {
1903                         size = (modlist->sml_numvals+1) * sizeof(struct berval);
1904                         if ( modlist->sml_nvalues ) size *= 2;
1905                 } else {
1906                         size = 0;
1907                 }
1908                 size += sizeof(Modifications);
1909                 mod = op->o_tmpalloc( size, op->o_tmpmemctx );
1910                 if ( !modnew )
1911                         modnew = mod;
1912                 if ( modtail )
1913                         modtail->sml_next = mod;
1914                 modtail = mod;
1915                 mod->sml_desc = modlist->sml_desc;
1916                 mod->sml_numvals = modlist->sml_numvals;
1917                 mod->sml_flags = 0;
1918                 if ( modlist->sml_numvals ) {
1919                         int i;
1920                         mod->sml_values = (BerVarray)(mod+1);
1921                         for (i=0; i<mod->sml_numvals; i++)
1922                                 mod->sml_values[i] = modlist->sml_values[i];
1923                         BER_BVZERO(&mod->sml_values[i]);
1924                         if ( modlist->sml_nvalues ) {
1925                                 mod->sml_nvalues = mod->sml_values + mod->sml_numvals + 1;
1926                                 for (i=0; i<mod->sml_numvals; i++)
1927                                         mod->sml_nvalues[i] = modlist->sml_nvalues[i];
1928                                 BER_BVZERO(&mod->sml_nvalues[i]);
1929                         } else {
1930                                 mod->sml_nvalues = NULL;
1931                         }
1932                 } else {
1933                         mod->sml_values = NULL;
1934                         mod->sml_nvalues = NULL;
1935                 }
1936                 if ( match < 0 && modlist->sml_op == LDAP_MOD_REPLACE )
1937                         mod->sml_op = LDAP_MOD_ADD;
1938                 else
1939                         mod->sml_op = modlist->sml_op;
1940                 mod->sml_next = NULL;
1941         }
1942         return modnew;
1943 }
1944
1945 typedef struct resolve_ctxt {
1946         syncinfo_t *rx_si;
1947         Modifications *rx_mods;
1948 } resolve_ctxt;
1949
1950 static void
1951 compare_vals( Modifications *m1, Modifications *m2 )
1952 {
1953         int i, j;
1954         struct berval *bv1, *bv2;
1955
1956         if ( m2->sml_nvalues ) {
1957                 bv2 = m2->sml_nvalues;
1958                 bv1 = m1->sml_nvalues;
1959         } else {
1960                 bv2 = m2->sml_values;
1961                 bv1 = m1->sml_values;
1962         }
1963         for ( j=0; j<m2->sml_numvals; j++ ) {
1964                 for ( i=0; i<m1->sml_numvals; i++ ) {
1965                         if ( !ber_bvcmp( &bv1[i], &bv2[j] )) {
1966                                 int k;
1967                                 for ( k=i; k<m1->sml_numvals-1; k++ ) {
1968                                         m1->sml_values[k] = m1->sml_values[k+1];
1969                                         if ( m1->sml_nvalues )
1970                                                 m1->sml_nvalues[k] = m1->sml_nvalues[k+1];
1971                                 }
1972                                 BER_BVZERO(&m1->sml_values[k]);
1973                                 if ( m1->sml_nvalues ) {
1974                                         BER_BVZERO(&m1->sml_nvalues[k]);
1975                                 }
1976                                 m1->sml_numvals--;
1977                                 i--;
1978                         }
1979                 }
1980         }
1981 }
1982
1983 static int
1984 syncrepl_resolve_cb( Operation *op, SlapReply *rs )
1985 {
1986         if ( rs->sr_type == REP_SEARCH ) {
1987                 resolve_ctxt *rx = op->o_callback->sc_private;
1988                 Attribute *a = attr_find( rs->sr_entry->e_attrs, ad_reqMod );
1989                 if ( a ) {
1990                         Modifications *oldmods, *newmods, *m1, *m2, **prev;
1991                         oldmods = rx->rx_mods;
1992                         syncrepl_accesslog_mods( rx->rx_si, a->a_vals, &newmods );
1993                         for ( m2 = newmods; m2; m2=m2->sml_next ) {
1994                                 for ( prev = &oldmods, m1 = *prev; m1; m1 = *prev ) {
1995                                         if ( m1->sml_desc != m2->sml_desc ) {
1996                                                 prev = &m1->sml_next;
1997                                                 continue;
1998                                         }
1999                                         if ( m2->sml_op == LDAP_MOD_DELETE ||
2000                                                 m2->sml_op == LDAP_MOD_REPLACE ) {
2001                                                 int numvals = m2->sml_numvals;
2002                                                 if ( m2->sml_op == LDAP_MOD_REPLACE )
2003                                                         numvals = 0;
2004                                                 /* New delete All cancels everything */
2005                                                 if ( numvals == 0 ) {
2006 drop:
2007                                                         *prev = m1->sml_next;
2008                                                         op->o_tmpfree( m1, op->o_tmpmemctx );
2009                                                         continue;
2010                                                 }
2011                                                 if ( m1->sml_op == LDAP_MOD_DELETE ) {
2012                                                         if ( m1->sml_numvals == 0 ) {
2013                                                                 /* turn this to SOFTDEL later */
2014                                                                 m1->sml_flags = SLAP_MOD_INTERNAL;
2015                                                         } else {
2016                                                                 compare_vals( m1, m2 );
2017                                                                 if ( !m1->sml_numvals )
2018                                                                         goto drop;
2019                                                         }
2020                                                 } else if ( m1->sml_op == LDAP_MOD_ADD ) {
2021                                                         compare_vals( m1, m2 );
2022                                                         if ( !m1->sml_numvals )
2023                                                                 goto drop;
2024                                                 }
2025                                         }
2026
2027                                         if ( m2->sml_op == LDAP_MOD_ADD ||
2028                                                 m2->sml_op == LDAP_MOD_REPLACE ) {
2029                                                 if ( m1->sml_op == LDAP_MOD_DELETE ) {
2030                                                         if ( !m1->sml_numvals ) goto drop;
2031                                                         compare_vals( m1, m2 );
2032                                                         if ( !m1->sml_numvals )
2033                                                                 goto drop;
2034                                                 }
2035                                                 if ( m2->sml_desc->ad_type->sat_atype.at_single_value )
2036                                                         goto drop;
2037                                                 compare_vals( m1, m2 );
2038                                                 if ( !m1->sml_numvals )
2039                                                         goto drop;
2040                                         }
2041                                         prev = &m1->sml_next;
2042                                 }
2043                         }
2044                         slap_mods_free( newmods, 1 );
2045                         rx->rx_mods = oldmods;
2046                 }
2047         }
2048         return LDAP_SUCCESS;
2049 }
2050
2051 typedef struct modify_ctxt {
2052         Modifications *mx_orig;
2053         Modifications *mx_free;
2054 } modify_ctxt;
2055
2056 static int
2057 syncrepl_modify_cb( Operation *op, SlapReply *rs )
2058 {
2059         slap_callback *sc = op->o_callback;
2060         modify_ctxt *mx = sc->sc_private;
2061         Modifications *ml;
2062
2063         op->orm_no_opattrs = 0;
2064         op->orm_modlist = mx->mx_orig;
2065         for ( ml = mx->mx_free; ml; ml = mx->mx_free ) {
2066                 mx->mx_free = ml->sml_next;
2067                 op->o_tmpfree( ml, op->o_tmpmemctx );
2068         }
2069         op->o_callback = sc->sc_next;
2070         op->o_tmpfree( sc, op->o_tmpmemctx );
2071         return SLAP_CB_CONTINUE;
2072 }
2073
2074 static int
2075 syncrepl_op_modify( Operation *op, SlapReply *rs )
2076 {
2077         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2078         OpExtra *oex;
2079         syncinfo_t *si;
2080         Entry *e;
2081         int rc, match = 0;
2082         Modifications *mod, *newlist;
2083
2084         LDAP_SLIST_FOREACH( oex, &op->o_extra, oe_next ) {
2085                 if ( oex->oe_key == (void *)syncrepl_message_to_op )
2086                         break;
2087         }
2088         if ( !oex )
2089                 return SLAP_CB_CONTINUE;
2090
2091         si = ((OpExtraSync *)oex)->oe_si;
2092
2093         /* Check if entryCSN in modlist is newer than entryCSN in entry.
2094          * We do it here because the op has been serialized by accesslog
2095          * by the time we get here. If the CSN is new enough, just do the
2096          * mod. If not, we need to resolve conflicts.
2097          */
2098
2099         for ( mod = op->orm_modlist; mod; mod=mod->sml_next ) {
2100                 if ( mod->sml_desc == slap_schema.si_ad_entryCSN ) break;
2101         }
2102         /* FIXME: what should we do if entryCSN is missing from the mod? */
2103         if ( !mod )
2104                 return SLAP_CB_CONTINUE;
2105
2106         {
2107                 int i, sid;
2108                 sid = slap_parse_csn_sid( &mod->sml_nvalues[0] );
2109                 ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
2110                 for ( i =0; i<si->si_cookieState->cs_num; i++ ) {
2111 #ifdef CHATTY_SYNCLOG
2112                         Debug( LDAP_DEBUG_SYNC, "syncrepl_op_modify: %s CSN for sid %d: %s\n",
2113                                 si->si_ridtxt, i, si->si_cookieState->cs_vals[i].bv_val );
2114 #endif
2115                         /* new SID */
2116                         if ( sid < si->si_cookieState->cs_sids[i] )
2117                                 break;
2118                         if ( si->si_cookieState->cs_sids[i] == sid ) {
2119                                 if ( ber_bvcmp( &mod->sml_nvalues[0], &si->si_cookieState->cs_vals[i] ) <= 0 ) {
2120                                         Debug( LDAP_DEBUG_SYNC, "syncrepl_op_modify: %s entryCSN too old, ignoring %s (%s)\n",
2121                                                 si->si_ridtxt, mod->sml_nvalues[0].bv_val, op->o_req_dn.bv_val );
2122                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2123                                         slap_graduate_commit_csn( op );
2124                                         /* tell accesslog this was a failure */
2125                                         rs->sr_err = LDAP_TYPE_OR_VALUE_EXISTS;
2126                                         return LDAP_SUCCESS;
2127                                 }
2128                         }
2129                 }
2130                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2131         }
2132
2133         rc = overlay_entry_get_ov( op, &op->o_req_ndn, NULL, NULL, 0, &e, on );
2134         if ( rc == 0 ) {
2135                 Attribute *a;
2136                 const char *text;
2137                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryCSN );
2138                 value_match( &match, slap_schema.si_ad_entryCSN,
2139                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
2140                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
2141                         &mod->sml_nvalues[0], &a->a_nvals[0], &text );
2142                 overlay_entry_release_ov( op, e, 0, on );
2143         }
2144         /* equal? Should never happen */
2145         if ( match == 0 ) {
2146                 slap_graduate_commit_csn( op );
2147                 /* tell accesslog this was a failure */
2148                 rs->sr_err = LDAP_TYPE_OR_VALUE_EXISTS;
2149                 return LDAP_SUCCESS;
2150         }
2151
2152         /* mod is older: resolve conflicts...
2153          * 1. Save/copy original modlist. Split Replace to Del/Add.
2154          * 2. Find all mods to this reqDN newer than the mod stamp.
2155          * 3. Resolve any mods in this request that affect attributes
2156          *    touched by newer mods.
2157          *    old         new
2158          *    delete all  delete all  drop
2159          *    delete all  delete X    SOFTDEL
2160          *    delete X    delete all  drop
2161          *    delete X    delete X    drop
2162          *    delete X    delete Y    OK
2163          *    delete all  add X       drop
2164          *    delete X    add X       drop
2165          *    delete X    add Y       OK
2166          *    add X       delete all  drop
2167          *    add X       delete X    drop
2168          *    add X       add X       drop
2169          *    add X       add Y       if SV, drop else OK
2170          *
2171          * 4. Swap original modlist back in response callback so
2172          *    that accesslog logs the original mod.
2173          *
2174          * Even if the mod is newer, other out-of-order changes may
2175          * have been committed, forcing us to tweak the modlist:
2176          * 1. Save/copy original modlist.
2177          * 2. Change deletes to soft deletes.
2178          * 3. Change Adds of single-valued attrs to Replace.
2179          */
2180
2181         newlist = mods_dup( op, op->orm_modlist, match );
2182
2183         /* mod is older */
2184         if ( match < 0 ) {
2185                 Operation op2 = *op;
2186                 AttributeName an[2];
2187                 const char *text;
2188                 struct berval bv;
2189                 char *ptr;
2190                 Modifications *ml;
2191                 int size, rc;
2192                 SlapReply rs1 = {0};
2193                 resolve_ctxt rx;
2194                 slap_callback cb = { NULL, syncrepl_resolve_cb, NULL, NULL };
2195         Filter lf[3] = {0};
2196         AttributeAssertion aa[2] = {0};
2197
2198                 rx.rx_si = si;
2199                 rx.rx_mods = newlist;
2200                 cb.sc_private = &rx;
2201
2202                 op2.o_tag = LDAP_REQ_SEARCH;
2203                 op2.ors_scope = LDAP_SCOPE_SUBTREE;
2204                 op2.ors_deref = LDAP_DEREF_NEVER;
2205                 op2.o_req_dn = si->si_logbase;
2206                 op2.o_req_ndn = si->si_logbase;
2207                 op2.ors_tlimit = SLAP_NO_LIMIT;
2208                 op2.ors_slimit = SLAP_NO_LIMIT;
2209                 op2.ors_limit = NULL;
2210                 memset( an, 0, sizeof(an));
2211                 an[0].an_desc = ad_reqMod;
2212                 an[0].an_name = ad_reqMod->ad_cname;
2213                 op2.ors_attrs = an;
2214                 op2.ors_attrsonly = 0;
2215
2216                 bv = mod->sml_nvalues[0];
2217
2218                 size = sizeof("(&(entryCSN>=)(reqDN=))");
2219                 size += bv.bv_len + op->o_req_ndn.bv_len + si->si_logfilterstr.bv_len;
2220                 op2.ors_filterstr.bv_val = op->o_tmpalloc( size, op->o_tmpmemctx );
2221                 op2.ors_filterstr.bv_len = sprintf(op2.ors_filterstr.bv_val,
2222                         "(&(entryCSN>=%s)(reqDN=%s)%s)",
2223                         bv.bv_val, op->o_req_ndn.bv_val, si->si_logfilterstr.bv_val );
2224
2225         lf[0].f_choice = LDAP_FILTER_AND;
2226         lf[0].f_and = lf+1;
2227         lf[1].f_choice = LDAP_FILTER_GE;
2228         lf[1].f_ava = aa;
2229         lf[1].f_av_desc = slap_schema.si_ad_entryCSN;
2230         lf[1].f_av_value = bv;
2231         lf[1].f_next = lf+2;
2232         lf[2].f_choice = LDAP_FILTER_EQUALITY;
2233         lf[2].f_ava = aa+1;
2234         lf[2].f_av_desc = ad_reqDN;
2235         lf[2].f_av_value = op->o_req_ndn;
2236         lf[2].f_next = si->si_logfilter;
2237
2238                 op2.ors_filter = lf;
2239
2240                 op2.o_callback = &cb;
2241                 op2.o_bd = select_backend( &op2.o_req_ndn, 1 );
2242                 op2.o_bd->be_search( &op2, &rs1 );
2243                 newlist = rx.rx_mods;
2244         }
2245
2246         {
2247                 slap_callback *sc = op->o_tmpalloc( sizeof(slap_callback) +
2248                         sizeof(modify_ctxt), op->o_tmpmemctx );
2249                 modify_ctxt *mx = (modify_ctxt *)(sc+1);
2250                 Modifications *ml;
2251
2252                 sc->sc_response = syncrepl_modify_cb;
2253                 sc->sc_private = mx;
2254                 sc->sc_next = op->o_callback;
2255                 sc->sc_cleanup = NULL;
2256                 sc->sc_writewait = NULL;
2257                 op->o_callback = sc;
2258                 op->orm_no_opattrs = 1;
2259                 mx->mx_orig = op->orm_modlist;
2260                 mx->mx_free = newlist;
2261                 for ( ml = newlist; ml; ml=ml->sml_next ) {
2262                         if ( ml->sml_flags == SLAP_MOD_INTERNAL ) {
2263                                 ml->sml_flags = 0;
2264                                 ml->sml_op = SLAP_MOD_SOFTDEL;
2265                         }
2266                         else if ( ml->sml_op == LDAP_MOD_DELETE )
2267                                 ml->sml_op = SLAP_MOD_SOFTDEL;
2268                         else if ( ml->sml_op == LDAP_MOD_ADD &&
2269                                 ml->sml_desc->ad_type->sat_atype.at_single_value )
2270                                 ml->sml_op = LDAP_MOD_REPLACE;
2271                 }
2272                 op->orm_modlist = newlist;
2273                 op->o_csn = mod->sml_nvalues[0];
2274         }
2275         return SLAP_CB_CONTINUE;
2276 }
2277
2278 static int
2279 syncrepl_message_to_op(
2280         syncinfo_t      *si,
2281         Operation       *op,
2282         LDAPMessage     *msg
2283 )
2284 {
2285         BerElement      *ber = NULL;
2286         Modifications   *modlist = NULL;
2287         logschema *ls;
2288         SlapReply rs = { REP_RESULT };
2289         slap_callback cb = { NULL, null_callback, NULL, NULL };
2290
2291         const char      *text;
2292         char txtbuf[SLAP_TEXT_BUFLEN];
2293         size_t textlen = sizeof txtbuf;
2294
2295         struct berval   bdn, dn = BER_BVNULL, ndn;
2296         struct berval   bv, bv2, *bvals = NULL;
2297         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
2298                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
2299                 psup = BER_BVNULL, nsup = BER_BVNULL;
2300         int             rc, deleteOldRdn = 0, freeReqDn = 0;
2301         int             do_graduate = 0;
2302
2303         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
2304                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
2305                         "Message type should be entry (%d)",
2306                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
2307                 return -1;
2308         }
2309
2310         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
2311                 ls = &accesslog_sc;
2312         else
2313                 ls = &changelog_sc;
2314
2315         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
2316
2317         if ( rc != LDAP_SUCCESS ) {
2318                 Debug( LDAP_DEBUG_ANY,
2319                         "syncrepl_message_to_op: %s dn get failed (%d)",
2320                         si->si_ridtxt, rc, 0 );
2321                 return rc;
2322         }
2323
2324         op->o_tag = LBER_DEFAULT;
2325         op->o_bd = si->si_wbe;
2326
2327         if ( BER_BVISEMPTY( &bdn )) {
2328                 Debug( LDAP_DEBUG_ANY,
2329                         "syncrepl_message_to_op: %s got empty dn",
2330                         si->si_ridtxt, 0, 0 );
2331                 return LDAP_OTHER;
2332         }
2333
2334         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
2335                 == LDAP_SUCCESS ) {
2336                 if ( bv.bv_val == NULL )
2337                         break;
2338
2339                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
2340                         bdn = bvals[0];
2341                         REWRITE_DN( si, bdn, bv2, dn, ndn );
2342                         if ( rc != LDAP_SUCCESS ) {
2343                                 Debug( LDAP_DEBUG_ANY,
2344                                         "syncrepl_message_to_op: %s "
2345                                         "dn \"%s\" normalization failed (%d)",
2346                                         si->si_ridtxt, bdn.bv_val, rc );
2347                                 rc = -1;
2348                                 ch_free( bvals );
2349                                 goto done;
2350                         }
2351                         ber_dupbv( &op->o_req_dn, &dn );
2352                         ber_dupbv( &op->o_req_ndn, &ndn );
2353                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
2354                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
2355                         freeReqDn = 1;
2356                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
2357                         int i = verb_to_mask( bvals[0].bv_val, modops );
2358                         if ( i < 0 ) {
2359                                 Debug( LDAP_DEBUG_ANY,
2360                                         "syncrepl_message_to_op: %s unknown op %s",
2361                                         si->si_ridtxt, bvals[0].bv_val, 0 );
2362                                 ch_free( bvals );
2363                                 rc = -1;
2364                                 goto done;
2365                         }
2366                         op->o_tag = modops[i].mask;
2367                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
2368                         /* Parse attribute into modlist */
2369                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
2370                                 rc = syncrepl_accesslog_mods( si, bvals, &modlist );
2371                         } else {
2372                                 rc = syncrepl_changelog_mods( si, bvals, &modlist );
2373                         }
2374                         if ( rc ) goto done;
2375                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
2376                         rdn = bvals[0];
2377                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
2378                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
2379                                 deleteOldRdn = 1;
2380                         }
2381                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
2382                         sup = bvals[0];
2383                 } else if ( !ber_bvstrcasecmp( &bv,
2384                         &slap_schema.si_ad_entryCSN->ad_cname ) )
2385                 {
2386                         slap_queue_csn( op, bvals );
2387                         do_graduate = 1;
2388                 }
2389                 ch_free( bvals );
2390         }
2391
2392         /* If we didn't get a mod type or a target DN, bail out */
2393         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
2394                 rc = -1;
2395                 goto done;
2396         }
2397
2398         op->o_callback = &cb;
2399         slap_op_time( &op->o_time, &op->o_tincr );
2400
2401         switch( op->o_tag ) {
2402         case LDAP_REQ_ADD:
2403         case LDAP_REQ_MODIFY:
2404                 /* If we didn't get required data, bail */
2405                 if ( !modlist ) goto done;
2406
2407                 rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
2408
2409                 if ( rc != LDAP_SUCCESS ) {
2410                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
2411                                 "mods check (%s)\n",
2412                                 si->si_ridtxt, text, 0 );
2413                         goto done;
2414                 }
2415
2416                 if ( op->o_tag == LDAP_REQ_ADD ) {
2417                         Entry *e = entry_alloc();
2418                         op->ora_e = e;
2419                         op->ora_e->e_name = op->o_req_dn;
2420                         op->ora_e->e_nname = op->o_req_ndn;
2421                         freeReqDn = 0;
2422                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
2423                         if( rc != LDAP_SUCCESS ) {
2424                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
2425                                 "mods2entry (%s)\n",
2426                                         si->si_ridtxt, text, 0 );
2427                         } else {
2428                                 rc = op->o_bd->be_add( op, &rs );
2429                                 Debug( LDAP_DEBUG_SYNC,
2430                                         "syncrepl_message_to_op: %s be_add %s (%d)\n", 
2431                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2432                                 do_graduate = 0;
2433                         }
2434                         if ( e == op->ora_e )
2435                                 be_entry_release_w( op, op->ora_e );
2436                 } else {
2437                         OpExtraSync oes;
2438                         op->orm_modlist = modlist;
2439                         op->o_bd = si->si_wbe;
2440                         /* delta-mmr needs additional checks in syncrepl_op_modify */
2441                         if ( SLAP_MULTIMASTER( op->o_bd )) {
2442                                 oes.oe.oe_key = (void *)syncrepl_message_to_op;
2443                                 oes.oe_si = si;
2444                                 LDAP_SLIST_INSERT_HEAD( &op->o_extra, &oes.oe, oe_next );
2445                         }
2446                         rc = op->o_bd->be_modify( op, &rs );
2447                         if ( SLAP_MULTIMASTER( op->o_bd )) {
2448                                 LDAP_SLIST_REMOVE( &op->o_extra, &oes.oe, OpExtra, oe_next );
2449                                 BER_BVZERO( &op->o_csn );
2450                         }
2451                         modlist = op->orm_modlist;
2452                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
2453                                 "syncrepl_message_to_op: %s be_modify %s (%d)\n", 
2454                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2455                         op->o_bd = si->si_be;
2456                         do_graduate = 0;
2457                 }
2458                 break;
2459         case LDAP_REQ_MODRDN:
2460                 if ( BER_BVISNULL( &rdn ) ) goto done;
2461
2462                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
2463                         goto done;
2464                 }
2465                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
2466                         goto done;
2467                 }
2468                 if ( !BER_BVISNULL( &sup ) ) {
2469                         REWRITE_DN( si, sup, bv2, psup, nsup );
2470                         if ( rc )
2471                                 goto done;
2472                         op->orr_newSup = &psup;
2473                         op->orr_nnewSup = &nsup;
2474                 } else {
2475                         op->orr_newSup = NULL;
2476                         op->orr_nnewSup = NULL;
2477                 }
2478                 op->orr_newrdn = prdn;
2479                 op->orr_nnewrdn = nrdn;
2480                 op->orr_deleteoldrdn = deleteOldRdn;
2481                 op->orr_modlist = NULL;
2482                 if ( slap_modrdn2mods( op, &rs ) ) {
2483                         goto done;
2484                 }
2485
2486                 /* Append modlist for operational attrs */
2487                 {
2488                         Modifications *m;
2489
2490                         for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
2491                                 ;
2492                         m->sml_next = modlist;
2493                         modlist = NULL;
2494                 }
2495                 rc = op->o_bd->be_modrdn( op, &rs );
2496                 slap_mods_free( op->orr_modlist, 1 );
2497                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
2498                         "syncrepl_message_to_op: %s be_modrdn %s (%d)\n", 
2499                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2500                 do_graduate = 0;
2501                 break;
2502         case LDAP_REQ_DELETE:
2503                 rc = op->o_bd->be_delete( op, &rs );
2504                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
2505                         "syncrepl_message_to_op: %s be_delete %s (%d)\n", 
2506                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2507                 do_graduate = 0;
2508                 break;
2509         }
2510 done:
2511         if ( do_graduate )
2512                 slap_graduate_commit_csn( op );
2513         op->o_bd = si->si_be;
2514         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2515         BER_BVZERO( &op->o_csn );
2516         if ( modlist ) {
2517                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
2518         }
2519         if ( !BER_BVISNULL( &rdn ) ) {
2520                 if ( !BER_BVISNULL( &nsup ) ) {
2521                         ch_free( nsup.bv_val );
2522                 }
2523                 if ( !BER_BVISNULL( &psup ) ) {
2524                         ch_free( psup.bv_val );
2525                 }
2526                 if ( !BER_BVISNULL( &nrdn ) ) {
2527                         ch_free( nrdn.bv_val );
2528                 }
2529                 if ( !BER_BVISNULL( &prdn ) ) {
2530                         ch_free( prdn.bv_val );
2531                 }
2532         }
2533         if ( freeReqDn ) {
2534                 ch_free( op->o_req_ndn.bv_val );
2535                 ch_free( op->o_req_dn.bv_val );
2536         }
2537         ber_free( ber, 0 );
2538         return rc;
2539 }
2540
2541 static int
2542 syncrepl_message_to_entry(
2543         syncinfo_t      *si,
2544         Operation       *op,
2545         LDAPMessage     *msg,
2546         Modifications   **modlist,
2547         Entry                   **entry,
2548         int             syncstate,
2549         struct berval   *syncUUID
2550 )
2551 {
2552         Entry           *e = NULL;
2553         BerElement      *ber = NULL;
2554         Modifications   tmp;
2555         Modifications   *mod;
2556         Modifications   **modtail = modlist;
2557
2558         const char      *text;
2559         char txtbuf[SLAP_TEXT_BUFLEN];
2560         size_t textlen = sizeof txtbuf;
2561
2562         struct berval   bdn = BER_BVNULL, dn, ndn, bv2;
2563         int             rc, is_ctx;
2564
2565         *modlist = NULL;
2566
2567         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
2568                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
2569                         "Message type should be entry (%d)",
2570                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
2571                 return -1;
2572         }
2573
2574         op->o_tag = LDAP_REQ_ADD;
2575
2576         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
2577         if ( rc != LDAP_SUCCESS ) {
2578                 Debug( LDAP_DEBUG_ANY,
2579                         "syncrepl_message_to_entry: %s dn get failed (%d)",
2580                         si->si_ridtxt, rc, 0 );
2581                 return rc;
2582         }
2583
2584         if ( BER_BVISEMPTY( &bdn ) && !BER_BVISEMPTY( &op->o_bd->be_nsuffix[0] ) ) {
2585                 Debug( LDAP_DEBUG_ANY,
2586                         "syncrepl_message_to_entry: %s got empty dn",
2587                         si->si_ridtxt, 0, 0 );
2588                 return LDAP_OTHER;
2589         }
2590
2591         /* syncUUID[0] is normalized UUID received over the wire
2592          * syncUUID[1] is denormalized UUID, generated here
2593          */
2594         (void)slap_uuidstr_from_normalized( &syncUUID[1], &syncUUID[0], op->o_tmpmemctx );
2595         Debug( LDAP_DEBUG_SYNC,
2596                 "syncrepl_message_to_entry: %s DN: %s, UUID: %s\n",
2597                 si->si_ridtxt, bdn.bv_val, syncUUID[1].bv_val );
2598
2599         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
2600                 /* NOTE: this could be done even before decoding the DN,
2601                  * although encoding errors wouldn't be detected */
2602                 rc = LDAP_SUCCESS;
2603                 goto done;
2604         }
2605
2606         if ( entry == NULL ) {
2607                 return -1;
2608         }
2609
2610         REWRITE_DN( si, bdn, bv2, dn, ndn );
2611         if ( rc != LDAP_SUCCESS ) {
2612                 /* One of the things that could happen is that the schema
2613                  * is not lined-up; this could result in unknown attributes.
2614                  * A value non conformant to the syntax should be unlikely,
2615                  * except when replicating between different versions
2616                  * of the software, or when syntax validation bugs are fixed
2617                  */
2618                 Debug( LDAP_DEBUG_ANY,
2619                         "syncrepl_message_to_entry: "
2620                         "%s dn \"%s\" normalization failed (%d)",
2621                         si->si_ridtxt, bdn.bv_val, rc );
2622                 return rc;
2623         }
2624
2625         ber_dupbv( &op->o_req_dn, &dn );
2626         ber_dupbv( &op->o_req_ndn, &ndn );
2627         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
2628         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
2629
2630         is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
2631
2632         e = entry_alloc();
2633         e->e_name = op->o_req_dn;
2634         e->e_nname = op->o_req_ndn;
2635
2636         while ( ber_remaining( ber ) ) {
2637                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
2638                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
2639                 {
2640                         break;
2641                 }
2642
2643                 /* Drop all updates to the contextCSN of the context entry
2644                  * (ITS#4622, etc.)
2645                  */
2646                 if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
2647                         slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
2648                         ber_bvarray_free( tmp.sml_values );
2649                         continue;
2650                 }
2651
2652                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
2653
2654                 mod->sml_op = LDAP_MOD_REPLACE;
2655                 mod->sml_flags = 0;
2656                 mod->sml_next = NULL;
2657                 mod->sml_desc = NULL;
2658                 mod->sml_type = tmp.sml_type;
2659                 mod->sml_values = tmp.sml_values;
2660                 mod->sml_nvalues = NULL;
2661                 mod->sml_numvals = 0;   /* slap_mods_check will set this */
2662
2663 #ifdef ENABLE_REWRITE
2664                 if (si->si_rewrite) {
2665                         AttributeDescription *ad = NULL;
2666                         slap_bv2ad( &tmp.sml_type, &ad, &text );
2667                         if ( ad ) {
2668                                 mod->sml_desc = ad;
2669                                 mod->sml_type = ad->ad_cname;
2670                                 if ( ad->ad_type->sat_syntax == slap_schema.si_syn_distinguishedName ) {
2671                                         int i;
2672                                         for ( i = 0; tmp.sml_values[i].bv_val; i++ ) {
2673                                                 syncrepl_rewrite_dn( si, &tmp.sml_values[i], &bv2);
2674                                                 if ( !BER_BVISNULL( &bv2 )) {
2675                                                         ber_memfree( tmp.sml_values[i].bv_val );
2676                                                         tmp.sml_values[i] = bv2;
2677                                                 }
2678                                         }
2679                                 }
2680                         }
2681                 }
2682 #endif
2683                 *modtail = mod;
2684                 modtail = &mod->sml_next;
2685         }
2686
2687         if ( *modlist == NULL ) {
2688                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
2689                         si->si_ridtxt, 0, 0 );
2690                 rc = -1;
2691                 goto done;
2692         }
2693
2694         rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
2695
2696         if ( rc != LDAP_SUCCESS ) {
2697                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
2698                         si->si_ridtxt, text, 0 );
2699                 goto done;
2700         }
2701
2702         /* Strip out dynamically generated attrs */
2703         for ( modtail = modlist; *modtail ; ) {
2704                 mod = *modtail;
2705                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
2706                         *modtail = mod->sml_next;
2707                         slap_mod_free( &mod->sml_mod, 0 );
2708                         ch_free( mod );
2709                 } else {
2710                         modtail = &mod->sml_next;
2711                 }
2712         }
2713
2714         /* Strip out attrs in exattrs list */
2715         for ( modtail = modlist; *modtail ; ) {
2716                 mod = *modtail;
2717                 if ( ldap_charray_inlist( si->si_exattrs,
2718                         mod->sml_desc->ad_type->sat_cname.bv_val ) )
2719                 {
2720                         *modtail = mod->sml_next;
2721                         slap_mod_free( &mod->sml_mod, 0 );
2722                         ch_free( mod );
2723                 } else {
2724                         modtail = &mod->sml_next;
2725                 }
2726         }
2727
2728         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
2729         if( rc != LDAP_SUCCESS ) {
2730                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
2731                         si->si_ridtxt, text, 0 );
2732         }
2733
2734 done:
2735         ber_free( ber, 0 );
2736         if ( rc != LDAP_SUCCESS ) {
2737                 if ( e ) {
2738                         entry_free( e );
2739                         e = NULL;
2740                 }
2741         }
2742         if ( entry )
2743                 *entry = e;
2744
2745         return rc;
2746 }
2747
2748 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
2749
2750 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
2751  * entry if a previous refresh was interrupted before sending us a new
2752  * context state. We try to compare the new entry to the existing entry
2753  * and ignore the new entry if they are the same.
2754  *
2755  * Also, we may get an update where the entryDN has changed, due to
2756  * a ModDn on the provider. We detect this as well, so we can issue
2757  * the corresponding operation locally.
2758  *
2759  * In the case of a modify, we get a list of all the attributes
2760  * in the original entry. Rather than deleting the entry and re-adding it,
2761  * we issue a Modify request that deletes all the attributes and adds all
2762  * the new ones. This avoids the issue of trying to delete/add a non-leaf
2763  * entry.
2764  *
2765  * We otherwise distinguish ModDN from Modify; in the case of
2766  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
2767  * operational attributes from the entry, and do a regular ModDN.
2768  */
2769 typedef struct dninfo {
2770         Entry *new_entry;
2771         struct berval dn;
2772         struct berval ndn;
2773         struct berval nnewSup;
2774         int renamed;    /* Was an existing entry renamed? */
2775         int delOldRDN;  /* Was old RDN deleted? */
2776         Modifications **modlist;        /* the modlist we received */
2777         Modifications *mods;    /* the modlist we compared */
2778         int oldNcount;          /* #values of old naming attr */
2779         AttributeDescription *oldDesc;  /* for renames */
2780         AttributeDescription *newDesc;  /* for renames */
2781 } dninfo;
2782
2783 #define HASHUUID        1
2784
2785 /* return 1 if inserted, 0 otherwise */
2786 static int
2787 presentlist_insert(
2788         syncinfo_t* si,
2789         struct berval *syncUUID )
2790 {
2791         char *val;
2792
2793 #ifdef HASHUUID
2794         Avlnode **av;
2795         unsigned short s;
2796
2797         if ( !si->si_presentlist )
2798                 si->si_presentlist = ch_calloc(65536, sizeof( Avlnode * ));
2799
2800         av = (Avlnode **)si->si_presentlist;
2801
2802         val = ch_malloc(UUIDLEN-2);
2803         memcpy(&s, syncUUID->bv_val, 2);
2804         memcpy(val, syncUUID->bv_val+2, UUIDLEN-2);
2805
2806         if ( avl_insert( &av[s], val,
2807                 syncuuid_cmp, avl_dup_error ) )
2808         {
2809                 ch_free( val );
2810                 return 0;
2811         }
2812 #else
2813         val = ch_malloc(UUIDLEN);
2814
2815         AC_MEMCPY( val, syncUUID->bv_val, UUIDLEN );
2816
2817         if ( avl_insert( &si->si_presentlist, val,
2818                 syncuuid_cmp, avl_dup_error ) )
2819         {
2820                 ch_free( val );
2821                 return 0;
2822         }
2823 #endif
2824
2825         return 1;
2826 }
2827
2828 static char *
2829 presentlist_find(
2830         Avlnode *av,
2831         struct berval *val )
2832 {
2833 #ifdef HASHUUID
2834         Avlnode **a2 = (Avlnode **)av;
2835         unsigned short s;
2836
2837         if (!av)
2838                 return NULL;
2839
2840         memcpy(&s, val->bv_val, 2);
2841         return avl_find( a2[s], val->bv_val+2, syncuuid_cmp );
2842 #else
2843         return avl_find( av, val->bv_val, syncuuid_cmp );
2844 #endif
2845 }
2846
2847 static int
2848 presentlist_free( Avlnode *av )
2849 {
2850 #ifdef HASHUUID
2851         Avlnode **a2 = (Avlnode **)av;
2852         int i, count = 0;
2853
2854         if ( av ) {
2855                 for (i=0; i<65536; i++) {
2856                         if (a2[i])
2857                                 count += avl_free( a2[i], ch_free );
2858                 }
2859                 ch_free( av );
2860         }
2861         return count;
2862 #else
2863         return avl_free( av, ch_free );
2864 #endif
2865 }
2866
2867 static void
2868 presentlist_delete(
2869         Avlnode **av,
2870         struct berval *val )
2871 {
2872 #ifdef HASHUUID
2873         Avlnode **a2 = *(Avlnode ***)av;
2874         unsigned short s;
2875
2876         memcpy(&s, val->bv_val, 2);
2877         avl_delete( &a2[s], val->bv_val+2, syncuuid_cmp );
2878 #else
2879         avl_delete( av, val->bv_val, syncuuid_cmp );
2880 #endif
2881 }
2882
2883 static int
2884 syncrepl_entry(
2885         syncinfo_t* si,
2886         Operation *op,
2887         Entry* entry,
2888         Modifications** modlist,
2889         int syncstate,
2890         struct berval* syncUUID,
2891         struct berval* syncCSN )
2892 {
2893         Backend *be = op->o_bd;
2894         slap_callback   cb = { NULL, NULL, NULL, NULL };
2895         int syncuuid_inserted = 0;
2896
2897         SlapReply       rs_search = {REP_RESULT};
2898         Filter f = {0};
2899         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2900         int rc = LDAP_SUCCESS;
2901
2902         struct berval pdn = BER_BVNULL;
2903         dninfo dni = {0};
2904         int     retry = 1;
2905         int     freecsn = 1;
2906
2907         Debug( LDAP_DEBUG_SYNC,
2908                 "syncrepl_entry: %s LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_%s)\n",
2909                 si->si_ridtxt, syncrepl_state2str( syncstate ), 0 );
2910
2911         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
2912                 if ( !si->si_refreshPresent && !si->si_refreshDone ) {
2913                         syncuuid_inserted = presentlist_insert( si, syncUUID );
2914                 }
2915         }
2916
2917         if ( syncstate == LDAP_SYNC_PRESENT ) {
2918                 return 0;
2919         } else if ( syncstate != LDAP_SYNC_DELETE ) {
2920                 if ( entry == NULL ) {
2921                         return 0;
2922                 }
2923         }
2924
2925         if ( syncstate != LDAP_SYNC_DELETE ) {
2926                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
2927
2928                 if ( a == NULL ) {
2929                         /* add if missing */
2930                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
2931                                 &syncUUID[1], syncUUID );
2932
2933                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
2934                         /* replace only if necessary */
2935                         if ( a->a_nvals != a->a_vals ) {
2936                                 ber_memfree( a->a_nvals[0].bv_val );
2937                                 ber_dupbv( &a->a_nvals[0], syncUUID );
2938                         }
2939                         ber_memfree( a->a_vals[0].bv_val );
2940                         ber_dupbv( &a->a_vals[0], &syncUUID[1] );
2941                 }
2942         }
2943
2944         f.f_choice = LDAP_FILTER_EQUALITY;
2945         f.f_ava = &ava;
2946         ava.aa_desc = slap_schema.si_ad_entryUUID;
2947         ava.aa_value = *syncUUID;
2948
2949         if ( syncuuid_inserted ) {
2950                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
2951                         si->si_ridtxt, syncUUID[1].bv_val, 0 );
2952         }
2953         op->ors_filter = &f;
2954
2955         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID[1].bv_len;
2956         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
2957                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
2958         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
2959         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
2960                 syncUUID[1].bv_val, syncUUID[1].bv_len );
2961         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
2962         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
2963
2964         op->o_tag = LDAP_REQ_SEARCH;
2965         op->ors_scope = LDAP_SCOPE_SUBTREE;
2966         op->ors_deref = LDAP_DEREF_NEVER;
2967
2968         /* get the entry for this UUID */
2969 #ifdef ENABLE_REWRITE
2970         if ( si->si_rewrite ) {
2971                 op->o_req_dn = si->si_suffixm;
2972                 op->o_req_ndn = si->si_suffixm;
2973         } else
2974 #endif
2975         {
2976                 op->o_req_dn = si->si_base;
2977                 op->o_req_ndn = si->si_base;
2978         }
2979
2980         op->o_time = slap_get_time();
2981         op->ors_tlimit = SLAP_NO_LIMIT;
2982         op->ors_slimit = 1;
2983         op->ors_limit = NULL;
2984
2985         op->ors_attrs = slap_anlist_all_attributes;
2986         op->ors_attrsonly = 0;
2987
2988         /* set callback function */
2989         op->o_callback = &cb;
2990         cb.sc_response = dn_callback;
2991         cb.sc_private = &dni;
2992         dni.new_entry = entry;
2993         dni.modlist = modlist;
2994
2995         rc = be->be_search( op, &rs_search );
2996         Debug( LDAP_DEBUG_SYNC,
2997                         "syncrepl_entry: %s be_search (%d)\n", 
2998                         si->si_ridtxt, rc, 0 );
2999
3000         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
3001                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
3002         }
3003
3004         cb.sc_response = null_callback;
3005         cb.sc_private = si;
3006
3007         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
3008                 Debug( LDAP_DEBUG_SYNC,
3009                                 "syncrepl_entry: %s %s\n",
3010                                 si->si_ridtxt, entry->e_name.bv_val, 0 );
3011         } else {
3012                 Debug( LDAP_DEBUG_SYNC,
3013                                 "syncrepl_entry: %s %s\n",
3014                                 si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
3015         }
3016
3017         assert( BER_BVISNULL( &op->o_csn ) );
3018         if ( syncCSN ) {
3019                 slap_queue_csn( op, syncCSN );
3020         }
3021
3022         if ( !si->si_refreshDone ) {
3023                 if ( si->si_lazyCommit )
3024                         op->o_lazyCommit = SLAP_CONTROL_NONCRITICAL;
3025                 if ( si->si_refreshCount == 500 ) {
3026                         LDAP_SLIST_REMOVE( &op->o_extra, si->si_refreshTxn, OpExtra, oe_next );
3027                         op->o_bd->bd_info->bi_op_txn( op, SLAP_TXN_COMMIT, &si->si_refreshTxn );
3028                         si->si_refreshCount = 0;
3029                         si->si_refreshTxn = NULL;
3030                 }
3031                 if ( op->o_bd->bd_info->bi_op_txn ) {
3032                         if ( !si->si_refreshCount ) {
3033                                 op->o_bd->bd_info->bi_op_txn( op, SLAP_TXN_BEGIN, &si->si_refreshTxn );
3034                         }
3035                         si->si_refreshCount++;
3036                 }
3037         }
3038
3039         slap_op_time( &op->o_time, &op->o_tincr );
3040         switch ( syncstate ) {
3041         case LDAP_SYNC_ADD:
3042         case LDAP_SYNC_MODIFY:
3043                 if ( BER_BVISNULL( &op->o_csn ))
3044                 {
3045
3046                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
3047                         if ( a ) {
3048                                 /* FIXME: op->o_csn is assumed to be
3049                                  * on the thread's slab; this needs
3050                                  * to be cleared ASAP.
3051                                  */
3052                                 op->o_csn = a->a_vals[0];
3053                                 freecsn = 0;
3054                         }
3055                 }
3056 retry_add:;
3057                 if ( BER_BVISNULL( &dni.dn ) ) {
3058                         SlapReply       rs_add = {REP_RESULT};
3059
3060                         op->o_req_dn = entry->e_name;
3061                         op->o_req_ndn = entry->e_nname;
3062                         op->o_tag = LDAP_REQ_ADD;
3063                         op->ora_e = entry;
3064                         op->o_bd = si->si_wbe;
3065
3066                         rc = op->o_bd->be_add( op, &rs_add );
3067                         Debug( LDAP_DEBUG_SYNC,
3068                                         "syncrepl_entry: %s be_add %s (%d)\n", 
3069                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3070                         switch ( rs_add.sr_err ) {
3071                         case LDAP_SUCCESS:
3072                                 if ( op->ora_e == entry ) {
3073                                         be_entry_release_w( op, entry );
3074                                 }
3075                                 entry = NULL;
3076                                 break;
3077
3078                         case LDAP_REFERRAL:
3079                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
3080                          * only if the suffix entry is not present.
3081                          * This should not happen during Persist phase.
3082                          */
3083                         case LDAP_NO_SUCH_OBJECT:
3084                                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST &&
3085                                         si->si_refreshDone ) {
3086                                         /* Something's wrong, start over */
3087                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
3088                                         si->si_syncCookie.ctxcsn = NULL;
3089                                         entry_free( entry );
3090                                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
3091                                         ber_bvarray_free( si->si_cookieState->cs_vals );
3092                                         ch_free( si->si_cookieState->cs_sids );
3093                                         si->si_cookieState->cs_vals = NULL;
3094                                         si->si_cookieState->cs_sids = 0;
3095                                         si->si_cookieState->cs_num = 0;
3096                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3097                                         return LDAP_NO_SUCH_OBJECT;
3098                                 }
3099                                 rc = syncrepl_add_glue( op, entry );
3100                                 entry = NULL;
3101                                 break;
3102
3103                         /* if an entry was added via syncrepl_add_glue(),
3104                          * it likely has no entryUUID, so the previous
3105                          * be_search() doesn't find it.  In this case,
3106                          * give syncrepl a chance to modify it. Also
3107                          * allow for entries that were recreated with the
3108                          * same DN but a different entryUUID.
3109                          */
3110                         case LDAP_ALREADY_EXISTS:
3111                                 if ( retry ) {
3112                                         Operation       op2 = *op;
3113                                         SlapReply       rs2 = { REP_RESULT };
3114                                         slap_callback   cb2 = { 0 };
3115
3116                                         op2.o_bd = be;
3117                                         op2.o_tag = LDAP_REQ_SEARCH;
3118                                         op2.o_req_dn = entry->e_name;
3119                                         op2.o_req_ndn = entry->e_nname;
3120                                         op2.ors_scope = LDAP_SCOPE_BASE;
3121                                         op2.ors_deref = LDAP_DEREF_NEVER;
3122                                         op2.ors_attrs = slap_anlist_all_attributes;
3123                                         op2.ors_attrsonly = 0;
3124                                         op2.ors_limit = NULL;
3125                                         op2.ors_slimit = 1;
3126                                         op2.ors_tlimit = SLAP_NO_LIMIT;
3127
3128                                         f.f_choice = LDAP_FILTER_PRESENT;
3129                                         f.f_desc = slap_schema.si_ad_objectClass;
3130                                         op2.ors_filter = &f;
3131                                         op2.ors_filterstr = generic_filterstr;
3132
3133                                         op2.o_callback = &cb2;
3134                                         cb2.sc_response = dn_callback;
3135                                         cb2.sc_private = &dni;
3136
3137                                         rc = be->be_search( &op2, &rs2 );
3138                                         if ( rc ) goto done;
3139
3140                                         retry = 0;
3141                                         slap_op_time( &op->o_time, &op->o_tincr );
3142                                         goto retry_add;
3143                                 }
3144                                 /* FALLTHRU */
3145
3146                         default:
3147                                 Debug( LDAP_DEBUG_ANY,
3148                                         "syncrepl_entry: %s be_add %s failed (%d)\n",
3149                                         si->si_ridtxt, op->o_req_dn.bv_val, rs_add.sr_err );
3150                                 break;
3151                         }
3152                         syncCSN = NULL;
3153                         op->o_bd = be;
3154                         goto done;
3155                 }
3156                 /* FALLTHRU */
3157                 op->o_req_dn = dni.dn;
3158                 op->o_req_ndn = dni.ndn;
3159                 if ( dni.renamed ) {
3160                         struct berval noldp, newp;
3161                         Modifications *mod, **modtail, **ml, *m2;
3162                         int i, got_replace = 0, just_rename = 0;
3163                         SlapReply rs_modify = {REP_RESULT};
3164
3165                         op->o_tag = LDAP_REQ_MODRDN;
3166                         dnRdn( &entry->e_name, &op->orr_newrdn );
3167                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
3168
3169                         if ( !BER_BVISNULL( &dni.nnewSup )) {
3170                                 dnParent( &entry->e_name, &newp );
3171                                 op->orr_newSup = &newp;
3172                                 op->orr_nnewSup = &dni.nnewSup;
3173                         } else {
3174                                 op->orr_newSup = NULL;
3175                                 op->orr_nnewSup = NULL;
3176                         }
3177                         op->orr_deleteoldrdn = dni.delOldRDN;
3178                         op->orr_modlist = NULL;
3179                         if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
3180                                 goto done;
3181                         }
3182
3183                         /* Drop the RDN-related mods from this op, because their
3184                          * equivalents were just setup by slap_modrdn2mods.
3185                          *
3186                          * If delOldRDN is TRUE then we should see a delete modop
3187                          * for oldDesc. We might see a replace instead.
3188                          *  delete with no values: therefore newDesc != oldDesc.
3189                          *   if oldNcount == 1, then Drop this op.
3190                          *  delete with 1 value: can only be the oldRDN value. Drop op.
3191                          *  delete with N values: Drop oldRDN value, keep remainder.
3192                          *  replace with 1 value: if oldNcount == 1 and
3193                          *     newDesc == oldDesc, Drop this op.
3194                          * Any other cases must be left intact.
3195                          *
3196                          * We should also see an add modop for newDesc. (But not if
3197                          * we got a replace modop due to delOldRDN.) If it has
3198                          * multiple values, we'll have to drop the new RDN value.
3199                          */
3200                         modtail = &op->orr_modlist;
3201                         if ( dni.delOldRDN ) {
3202                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
3203                                         if ( (*ml)->sml_desc == dni.oldDesc ) {
3204                                                 mod = *ml;
3205                                                 if ( mod->sml_op == LDAP_MOD_REPLACE &&
3206                                                         dni.oldDesc != dni.newDesc ) {
3207                                                         /* This Replace is due to other Mods.
3208                                                          * Just let it ride.
3209                                                          */
3210                                                         continue;
3211                                                 }
3212                                                 if ( mod->sml_numvals <= 1 &&
3213                                                         dni.oldNcount == 1 &&
3214                                                         ( mod->sml_op == LDAP_MOD_DELETE ||
3215                                                           mod->sml_op == LDAP_MOD_REPLACE )) {
3216                                                         if ( mod->sml_op == LDAP_MOD_REPLACE )
3217                                                                 got_replace = 1;
3218                                                         /* Drop this op */
3219                                                         *ml = mod->sml_next;
3220                                                         mod->sml_next = NULL;
3221                                                         slap_mods_free( mod, 1 );
3222                                                         break;
3223                                                 }
3224                                                 if ( mod->sml_op != LDAP_MOD_DELETE || mod->sml_numvals == 0 )
3225                                                         continue;
3226                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
3227                                                         if ( m2->sml_desc == dni.oldDesc &&
3228                                                                 m2->sml_op == LDAP_MOD_DELETE ) break;
3229                                                 }
3230                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
3231                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
3232                                                                 mod->sml_numvals--;
3233                                                                 ch_free( mod->sml_values[i].bv_val );
3234                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
3235                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
3236                                                                 if ( mod->sml_nvalues ) {
3237                                                                         ch_free( mod->sml_nvalues[i].bv_val );
3238                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
3239                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
3240                                                                 }
3241                                                                 break;
3242                                                         }
3243                                                 }
3244                                                 if ( !mod->sml_numvals ) {
3245                                                         /* Drop this op */
3246                                                         *ml = mod->sml_next;
3247                                                         mod->sml_next = NULL;
3248                                                         slap_mods_free( mod, 1 );
3249                                                 }
3250                                                 break;
3251                                         }
3252                                 }
3253                         }
3254                         if ( !got_replace ) {
3255                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
3256                                         if ( (*ml)->sml_desc == dni.newDesc ) {
3257                                                 mod = *ml;
3258                                                 if ( mod->sml_op != LDAP_MOD_ADD )
3259                                                         continue;
3260                                                 if ( mod->sml_numvals == 1 ) {
3261                                                         /* Drop this op */
3262                                                         *ml = mod->sml_next;
3263                                                         mod->sml_next = NULL;
3264                                                         slap_mods_free( mod, 1 );
3265                                                         break;
3266                                                 }
3267                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
3268                                                         if ( m2->sml_desc == dni.oldDesc &&
3269                                                                 m2->sml_op == SLAP_MOD_SOFTADD ) break;
3270                                                 }
3271                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
3272                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
3273                                                                 mod->sml_numvals--;
3274                                                                 ch_free( mod->sml_values[i].bv_val );
3275                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
3276                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
3277                                                                 if ( mod->sml_nvalues ) {
3278                                                                         ch_free( mod->sml_nvalues[i].bv_val );
3279                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
3280                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
3281                                                                 }
3282                                                                 break;
3283                                                         }
3284                                                 }
3285                                                 break;
3286                                         }
3287                                 }
3288                         }
3289
3290                         /* RDNs must be NUL-terminated for back-ldap */
3291                         noldp = op->orr_newrdn;
3292                         ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
3293                         noldp = op->orr_nnewrdn;
3294                         ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
3295
3296                         /* Setup opattrs too */
3297                         {
3298                                 static AttributeDescription *nullattr = NULL;
3299                                 static AttributeDescription **const opattrs[] = {
3300                                         &slap_schema.si_ad_entryCSN,
3301                                         &slap_schema.si_ad_modifiersName,
3302                                         &slap_schema.si_ad_modifyTimestamp,
3303                                         &nullattr
3304                                 };
3305                                 AttributeDescription *opattr;
3306                                 int i;
3307
3308                                 modtail = &m2;
3309                                 /* pull mod off incoming modlist */
3310                                 for ( i = 0; (opattr = *opattrs[i]) != NULL; i++ ) {
3311                                         for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next )
3312                                         {
3313                                                 if ( (*ml)->sml_desc == opattr ) {
3314                                                         mod = *ml;
3315                                                         *ml = mod->sml_next;
3316                                                         mod->sml_next = NULL;
3317                                                         *modtail = mod;
3318                                                         modtail = &mod->sml_next;
3319                                                         break;
3320                                                 }
3321                                         }
3322                                 }
3323                                 /* If there are still Modifications left, put the opattrs
3324                                  * back, and let be_modify run. Otherwise, append the opattrs
3325                                  * to the orr_modlist.
3326                                  */
3327                                 if ( dni.mods ) {
3328                                         mod = dni.mods;
3329                                         /* don't set a CSN for the rename op */
3330                                         if ( syncCSN )
3331                                                 slap_graduate_commit_csn( op );
3332                                 } else {
3333                                         mod = op->orr_modlist;
3334                                         just_rename = 1;
3335                                 }
3336                                 for ( ; mod->sml_next; mod=mod->sml_next );
3337                                 mod->sml_next = m2;
3338                         }
3339                         op->o_bd = si->si_wbe;
3340 retry_modrdn:;
3341                         rs_reinit( &rs_modify, REP_RESULT );
3342                         rc = op->o_bd->be_modrdn( op, &rs_modify );
3343
3344                         /* NOTE: noSuchObject should result because the new superior
3345                          * has not been added yet (ITS#6472) */
3346                         if ( rc == LDAP_NO_SUCH_OBJECT && op->orr_nnewSup != NULL ) {
3347                                 Operation op2 = *op;
3348                                 rc = syncrepl_add_glue_ancestors( &op2, entry );
3349                                 if ( rc == LDAP_SUCCESS ) {
3350                                         goto retry_modrdn;
3351                                 }
3352                         }
3353                 
3354                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
3355                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
3356
3357                         slap_mods_free( op->orr_modlist, 1 );
3358                         Debug( LDAP_DEBUG_SYNC,
3359                                         "syncrepl_entry: %s be_modrdn %s (%d)\n", 
3360                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3361                         op->o_bd = be;
3362                         /* Renamed entries may still have other mods so just fallthru */
3363                         op->o_req_dn = entry->e_name;
3364                         op->o_req_ndn = entry->e_nname;
3365                         /* Use CSN on the modify */
3366                         if ( just_rename )
3367                                 syncCSN = NULL;
3368                         else if ( syncCSN )
3369                                 slap_queue_csn( op, syncCSN );
3370                 }
3371                 if ( dni.mods ) {
3372                         SlapReply rs_modify = {REP_RESULT};
3373
3374                         op->o_tag = LDAP_REQ_MODIFY;
3375                         op->orm_modlist = dni.mods;
3376                         op->orm_no_opattrs = 1;
3377                         op->o_bd = si->si_wbe;
3378
3379                         rc = op->o_bd->be_modify( op, &rs_modify );
3380                         slap_mods_free( op->orm_modlist, 1 );
3381                         op->orm_no_opattrs = 0;
3382                         Debug( LDAP_DEBUG_SYNC,
3383                                         "syncrepl_entry: %s be_modify %s (%d)\n", 
3384                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3385                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
3386                                 Debug( LDAP_DEBUG_ANY,
3387                                         "syncrepl_entry: %s be_modify failed (%d)\n",
3388                                         si->si_ridtxt, rs_modify.sr_err, 0 );
3389                         }
3390                         syncCSN = NULL;
3391                         op->o_bd = be;
3392                 } else if ( !dni.renamed ) {
3393                         Debug( LDAP_DEBUG_SYNC,
3394                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
3395                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
3396                         if ( syncCSN ) {
3397                                 slap_graduate_commit_csn( op );
3398                                 syncCSN = NULL;
3399                         }
3400                 }
3401                 goto done;
3402         case LDAP_SYNC_DELETE :
3403                 if ( !BER_BVISNULL( &dni.dn ) ) {
3404                         SlapReply       rs_delete = {REP_RESULT};
3405                         op->o_req_dn = dni.dn;
3406                         op->o_req_ndn = dni.ndn;
3407                         op->o_tag = LDAP_REQ_DELETE;
3408                         op->o_bd = si->si_wbe;
3409                         if ( !syncCSN ) {
3410                                 slap_queue_csn( op, si->si_syncCookie.ctxcsn );
3411                         }
3412                         rc = op->o_bd->be_delete( op, &rs_delete );
3413                         Debug( LDAP_DEBUG_SYNC,
3414                                         "syncrepl_entry: %s be_delete %s (%d)\n", 
3415                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
3416                         if ( rc == LDAP_NO_SUCH_OBJECT )
3417                                 rc = LDAP_SUCCESS;
3418
3419                         while ( rs_delete.sr_err == LDAP_SUCCESS
3420                                 && op->o_delete_glue_parent ) {
3421                                 op->o_delete_glue_parent = 0;
3422                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
3423                                         slap_callback cb = { NULL };
3424                                         cb.sc_response = slap_null_cb;
3425                                         dnParent( &op->o_req_ndn, &pdn );
3426                                         op->o_req_dn = pdn;
3427                                         op->o_req_ndn = pdn;
3428                                         op->o_callback = &cb;
3429                                         rs_reinit( &rs_delete, REP_RESULT );
3430                                         op->o_bd->be_delete( op, &rs_delete );
3431                                 } else {
3432                                         break;
3433                                 }
3434                         }
3435                         syncCSN = NULL;
3436                         op->o_bd = be;
3437                 }
3438                 goto done;
3439
3440         default :
3441                 Debug( LDAP_DEBUG_ANY,
3442                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
3443                 goto done;
3444         }
3445
3446 done:
3447         slap_sl_free( syncUUID[1].bv_val, op->o_tmpmemctx );
3448         BER_BVZERO( &syncUUID[1] );
3449         if ( !BER_BVISNULL( &dni.ndn ) ) {
3450                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
3451         }
3452         if ( !BER_BVISNULL( &dni.dn ) ) {
3453                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
3454         }
3455         if ( entry ) {
3456                 entry_free( entry );
3457         }
3458         if ( syncCSN ) {
3459                 slap_graduate_commit_csn( op );
3460         }
3461         if ( !BER_BVISNULL( &op->o_csn ) && freecsn ) {
3462                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3463         }
3464         BER_BVZERO( &op->o_csn );
3465         return rc;
3466 }
3467
3468 static struct berval gcbva[] = {
3469         BER_BVC("top"),
3470         BER_BVC("glue"),
3471         BER_BVNULL
3472 };
3473
3474 #define NP_DELETE_ONE   2
3475
3476 static void
3477 syncrepl_del_nonpresent(
3478         Operation *op,
3479         syncinfo_t *si,
3480         BerVarray uuids,
3481         struct sync_cookie *sc,
3482         int m )
3483 {
3484         Backend* be = op->o_bd;
3485         slap_callback   cb = { NULL };
3486         struct nonpresent_entry *np_list, *np_prev;
3487         int rc;
3488         AttributeName   an[2];
3489
3490         struct berval pdn = BER_BVNULL;
3491         struct berval csn;
3492
3493 #ifdef ENABLE_REWRITE
3494         if ( si->si_rewrite ) {
3495                 op->o_req_dn = si->si_suffixm;
3496                 op->o_req_ndn = si->si_suffixm;
3497         } else
3498 #endif
3499         {
3500                 op->o_req_dn = si->si_base;
3501                 op->o_req_ndn = si->si_base;
3502         }
3503
3504         cb.sc_response = nonpresent_callback;
3505         cb.sc_private = si;
3506
3507         op->o_callback = &cb;
3508         op->o_tag = LDAP_REQ_SEARCH;
3509         op->ors_scope = si->si_scope;
3510         op->ors_deref = LDAP_DEREF_NEVER;
3511         op->o_time = slap_get_time();
3512         op->ors_tlimit = SLAP_NO_LIMIT;
3513
3514
3515         if ( uuids ) {
3516                 Filter uf;
3517                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
3518                 int i;
3519
3520                 op->ors_attrsonly = 1;
3521                 op->ors_attrs = slap_anlist_no_attrs;
3522                 op->ors_limit = NULL;
3523                 op->ors_filter = &uf;
3524
3525                 uf.f_ava = &eq;
3526                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
3527                 uf.f_next = NULL;
3528                 uf.f_choice = LDAP_FILTER_EQUALITY;
3529                 si->si_refreshDelete |= NP_DELETE_ONE;
3530
3531                 for (i=0; uuids[i].bv_val; i++) {
3532                         SlapReply rs_search = {REP_RESULT};
3533
3534                         op->ors_slimit = 1;
3535                         uf.f_av_value = uuids[i];
3536                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
3537                         rc = be->be_search( op, &rs_search );
3538                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
3539                 }
3540                 si->si_refreshDelete ^= NP_DELETE_ONE;
3541         } else {
3542                 Filter *cf, *of;
3543                 Filter mmf[2];
3544                 AttributeAssertion mmaa;
3545                 SlapReply rs_search = {REP_RESULT};
3546
3547                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
3548                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
3549                 an[0].an_desc = slap_schema.si_ad_entryUUID;
3550                 op->ors_attrs = an;
3551                 op->ors_slimit = SLAP_NO_LIMIT;
3552                 op->ors_tlimit = SLAP_NO_LIMIT;
3553                 op->ors_limit = NULL;
3554                 op->ors_attrsonly = 0;
3555                 op->ors_filter = filter_dup( si->si_filter, op->o_tmpmemctx );
3556                 /* In multimaster, updates can continue to arrive while
3557                  * we're searching. Limit the search result to entries
3558                  * older than our newest cookie CSN.
3559                  */
3560                 if ( SLAP_MULTIMASTER( op->o_bd )) {
3561                         Filter *f;
3562                         int i;
3563
3564                         f = mmf;
3565                         f->f_choice = LDAP_FILTER_AND;
3566                         f->f_next = op->ors_filter;
3567                         f->f_and = f+1;
3568                         of = f->f_and;
3569                         f = of;
3570                         f->f_choice = LDAP_FILTER_LE;
3571                         f->f_ava = &mmaa;
3572                         f->f_av_desc = slap_schema.si_ad_entryCSN;
3573                         f->f_next = NULL;
3574                         BER_BVZERO( &f->f_av_value );
3575                         for ( i=0; i<sc->numcsns; i++ ) {
3576                                 if ( ber_bvcmp( &sc->ctxcsn[i], &f->f_av_value ) > 0 )
3577                                         f->f_av_value = sc->ctxcsn[i];
3578                         }
3579                         of = op->ors_filter;
3580                         op->ors_filter = mmf;
3581                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
3582                 } else {
3583                         cf = NULL;
3584                         op->ors_filterstr = si->si_filterstr;
3585                 }
3586                 op->o_nocaching = 1;
3587
3588
3589                 rc = be->be_search( op, &rs_search );
3590                 if ( SLAP_MULTIMASTER( op->o_bd )) {
3591                         op->ors_filter = of;
3592                 }
3593                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter, 1 );
3594                 if ( op->ors_filterstr.bv_val != si->si_filterstr.bv_val ) {
3595                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
3596                 }
3597
3598         }
3599
3600         op->o_nocaching = 0;
3601
3602         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
3603
3604                 if ( sc->ctxcsn && !BER_BVISNULL( &sc->ctxcsn[m] ) ) {
3605                         csn = sc->ctxcsn[m];
3606                 } else {
3607                         csn = si->si_syncCookie.ctxcsn[0];
3608                 }
3609
3610                 op->o_bd = si->si_wbe;
3611                 slap_queue_csn( op, &csn );
3612
3613                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
3614                 while ( np_list != NULL ) {
3615                         SlapReply rs_delete = {REP_RESULT};
3616
3617                         LDAP_LIST_REMOVE( np_list, npe_link );
3618                         np_prev = np_list;
3619                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
3620                         op->o_tag = LDAP_REQ_DELETE;
3621                         op->o_callback = &cb;
3622                         cb.sc_response = null_callback;
3623                         cb.sc_private = si;
3624                         op->o_req_dn = *np_prev->npe_name;
3625                         op->o_req_ndn = *np_prev->npe_nname;
3626                         rc = op->o_bd->be_delete( op, &rs_delete );
3627                         Debug( LDAP_DEBUG_SYNC,
3628                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
3629                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
3630
3631                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
3632                                 SlapReply rs_modify = {REP_RESULT};
3633                                 Modifications mod1, mod2;
3634                                 mod1.sml_op = LDAP_MOD_REPLACE;
3635                                 mod1.sml_flags = 0;
3636                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
3637                                 mod1.sml_type = mod1.sml_desc->ad_cname;
3638                                 mod1.sml_numvals = 2;
3639                                 mod1.sml_values = &gcbva[0];
3640                                 mod1.sml_nvalues = NULL;
3641                                 mod1.sml_next = &mod2;
3642
3643                                 mod2.sml_op = LDAP_MOD_REPLACE;
3644                                 mod2.sml_flags = 0;
3645                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
3646                                 mod2.sml_type = mod2.sml_desc->ad_cname;
3647                                 mod2.sml_numvals = 1;
3648                                 mod2.sml_values = &gcbva[1];
3649                                 mod2.sml_nvalues = NULL;
3650                                 mod2.sml_next = NULL;
3651
3652                                 op->o_tag = LDAP_REQ_MODIFY;
3653                                 op->orm_modlist = &mod1;
3654
3655                                 rc = op->o_bd->be_modify( op, &rs_modify );
3656                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
3657                         }
3658
3659                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
3660                                         op->o_delete_glue_parent ) {
3661                                 op->o_delete_glue_parent = 0;
3662                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
3663                                         slap_callback cb = { NULL };
3664                                         cb.sc_response = slap_null_cb;
3665                                         dnParent( &op->o_req_ndn, &pdn );
3666                                         op->o_req_dn = pdn;
3667                                         op->o_req_ndn = pdn;
3668                                         op->o_callback = &cb;
3669                                         rs_reinit( &rs_delete, REP_RESULT );
3670                                         /* give it a root privil ? */
3671                                         op->o_bd->be_delete( op, &rs_delete );
3672                                 } else {
3673                                         break;
3674                                 }
3675                         }
3676
3677                         op->o_delete_glue_parent = 0;
3678
3679                         ber_bvfree( np_prev->npe_name );
3680                         ber_bvfree( np_prev->npe_nname );
3681                         ch_free( np_prev );
3682
3683                         if ( slapd_shutdown ) {
3684                                 break;
3685                         }
3686                 }
3687
3688                 slap_graduate_commit_csn( op );
3689                 op->o_bd = be;
3690
3691                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3692                 BER_BVZERO( &op->o_csn );
3693         }
3694
3695         return;
3696 }
3697
3698 static int
3699 syncrepl_add_glue_ancestors(
3700         Operation* op,
3701         Entry *e )
3702 {
3703         Backend *be = op->o_bd;
3704         slap_callback cb = { NULL };
3705         Attribute       *a;
3706         int     rc = LDAP_SUCCESS;
3707         int suffrdns;
3708         int i;
3709         struct berval dn = BER_BVNULL;
3710         struct berval ndn = BER_BVNULL;
3711         Entry   *glue;
3712         struct berval   ptr, nptr;
3713         char            *comma;
3714
3715         op->o_tag = LDAP_REQ_ADD;
3716         op->o_callback = &cb;
3717         cb.sc_response = null_callback;
3718         cb.sc_private = NULL;
3719
3720         dn = e->e_name;
3721         ndn = e->e_nname;
3722
3723         /* count RDNs in suffix */
3724         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
3725                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
3726                         comma++;
3727                         ptr.bv_len -= comma - ptr.bv_val;
3728                         ptr.bv_val = comma;
3729                         i++;
3730                 }
3731                 suffrdns = i;
3732         } else {
3733                 /* suffix is "" */
3734                 suffrdns = 0;
3735         }
3736
3737         /* Start with BE suffix */
3738         ptr = dn;
3739         for ( i = 0; i < suffrdns; i++ ) {
3740                 comma = ber_bvrchr( &ptr, ',' );
3741                 if ( comma != NULL ) {
3742                         ptr.bv_len = comma - ptr.bv_val;
3743                 } else {
3744                         ptr.bv_len = 0;
3745                         break;
3746                 }
3747         }
3748         
3749         if ( !BER_BVISEMPTY( &ptr ) ) {
3750                 dn.bv_len -= ptr.bv_len + ( suffrdns != 0 );
3751                 dn.bv_val += ptr.bv_len + ( suffrdns != 0 );
3752         }
3753
3754         /* the normalizedDNs are always the same length, no counting
3755          * required.
3756          */
3757         nptr = ndn;
3758         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
3759                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
3760                 ndn.bv_len = be->be_nsuffix[0].bv_len;
3761
3762                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
3763
3764         } else {
3765                 nptr.bv_len = 0;
3766         }
3767
3768         while ( ndn.bv_val > e->e_nname.bv_val ) {
3769                 SlapReply       rs_add = {REP_RESULT};
3770
3771                 glue = entry_alloc();
3772                 ber_dupbv( &glue->e_name, &dn );
3773                 ber_dupbv( &glue->e_nname, &ndn );
3774
3775                 a = attr_alloc( slap_schema.si_ad_objectClass );
3776
3777                 a->a_numvals = 2;
3778                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
3779                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
3780                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
3781                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
3782
3783                 a->a_nvals = a->a_vals;
3784
3785                 a->a_next = glue->e_attrs;
3786                 glue->e_attrs = a;
3787
3788                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
3789
3790                 a->a_numvals = 1;
3791                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
3792                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
3793                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
3794
3795                 a->a_nvals = a->a_vals;
3796
3797                 a->a_next = glue->e_attrs;
3798                 glue->e_attrs = a;
3799
3800                 op->o_req_dn = glue->e_name;
3801                 op->o_req_ndn = glue->e_nname;
3802                 op->ora_e = glue;
3803                 rc = be->be_add ( op, &rs_add );
3804                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
3805                         if ( op->ora_e == glue )
3806                                 be_entry_release_w( op, glue );
3807                 } else {
3808                 /* incl. ALREADY EXIST */
3809                         entry_free( glue );
3810                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
3811                                 entry_free( e );
3812                                 return rc;
3813                         }
3814                 }
3815
3816                 /* Move to next child */
3817                 comma = ber_bvrchr( &ptr, ',' );
3818                 if ( comma == NULL ) {
3819                         break;
3820                 }
3821                 ptr.bv_len = comma - ptr.bv_val;
3822                 
3823                 dn.bv_val = ++comma;
3824                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
3825
3826                 comma = ber_bvrchr( &nptr, ',' );
3827                 assert( comma != NULL );
3828                 nptr.bv_len = comma - nptr.bv_val;
3829
3830                 ndn.bv_val = ++comma;
3831                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
3832         }
3833
3834         return rc;
3835 }
3836
3837 int
3838 syncrepl_add_glue(
3839         Operation* op,
3840         Entry *e )
3841 {
3842         slap_callback cb = { NULL };
3843         int     rc;
3844         Backend *be = op->o_bd;
3845         SlapReply       rs_add = {REP_RESULT};
3846
3847         rc = syncrepl_add_glue_ancestors( op, e );
3848         switch ( rc ) {
3849         case LDAP_SUCCESS:
3850         case LDAP_ALREADY_EXISTS:
3851                 break;
3852
3853         default:
3854                 return rc;
3855         }
3856
3857         op->o_tag = LDAP_REQ_ADD;
3858         op->o_callback = &cb;
3859         cb.sc_response = null_callback;
3860         cb.sc_private = NULL;
3861
3862         op->o_req_dn = e->e_name;
3863         op->o_req_ndn = e->e_nname;
3864         op->ora_e = e;
3865         rc = be->be_add ( op, &rs_add );
3866         if ( rs_add.sr_err == LDAP_SUCCESS ) {
3867                 if ( op->ora_e == e )
3868                         be_entry_release_w( op, e );
3869         } else {
3870                 entry_free( e );
3871         }
3872
3873         return rc;
3874 }
3875
3876 static int
3877 syncrepl_updateCookie(
3878         syncinfo_t *si,
3879         Operation *op,
3880         struct sync_cookie *syncCookie )
3881 {
3882         Backend *be = op->o_bd;
3883         Modifications mod;
3884         struct berval first = BER_BVNULL;
3885         struct sync_cookie sc;
3886 #ifdef CHECK_CSN
3887         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
3888 #endif
3889
3890         int rc, i, j, changed = 0;
3891         ber_len_t len;
3892
3893         slap_callback cb = { NULL };
3894         SlapReply       rs_modify = {REP_RESULT};
3895
3896         mod.sml_op = LDAP_MOD_REPLACE;
3897         mod.sml_desc = slap_schema.si_ad_contextCSN;
3898         mod.sml_type = mod.sml_desc->ad_cname;
3899         mod.sml_flags = SLAP_MOD_INTERNAL;
3900         mod.sml_nvalues = NULL;
3901         mod.sml_next = NULL;
3902
3903         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
3904
3905 #ifdef CHECK_CSN
3906         for ( i=0; i<syncCookie->numcsns; i++ ) {
3907                 assert( !syn->ssyn_validate( syn, syncCookie->ctxcsn+i ));
3908         }
3909         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3910                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3911         }
3912 #endif
3913
3914         /* clone the cookieState CSNs so we can Replace the whole thing */
3915         sc.numcsns = si->si_cookieState->cs_num;
3916         if ( sc.numcsns ) {
3917                 ber_bvarray_dup_x( &sc.ctxcsn, si->si_cookieState->cs_vals, NULL );
3918                 sc.sids = ch_malloc( sc.numcsns * sizeof(int));
3919                 for ( i=0; i<sc.numcsns; i++ )
3920                         sc.sids[i] = si->si_cookieState->cs_sids[i];
3921         } else {
3922                 sc.ctxcsn = NULL;
3923                 sc.sids = NULL;
3924         }
3925
3926         /* find any CSNs in the syncCookie that are newer than the cookieState */
3927         for ( i=0; i<syncCookie->numcsns; i++ ) {
3928                 for ( j=0; j<sc.numcsns; j++ ) {
3929                         if ( syncCookie->sids[i] < sc.sids[j] )
3930                                 break;
3931                         if ( syncCookie->sids[i] != sc.sids[j] )
3932                                 continue;
3933                         len = syncCookie->ctxcsn[i].bv_len;
3934                         if ( len > sc.ctxcsn[j].bv_len )
3935                                 len = sc.ctxcsn[j].bv_len;
3936                         if ( memcmp( syncCookie->ctxcsn[i].bv_val,
3937                                 sc.ctxcsn[j].bv_val, len ) > 0 ) {
3938                                 ber_bvreplace( &sc.ctxcsn[j], &syncCookie->ctxcsn[i] );
3939                                 changed = 1;
3940                                 if ( BER_BVISNULL( &first ) ||
3941                                         memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 ) {
3942                                         first = syncCookie->ctxcsn[i];
3943                                 }
3944                         }
3945                         break;
3946                 }
3947                 /* there was no match for this SID, it's a new CSN */
3948                 if ( j == sc.numcsns ||
3949                         syncCookie->sids[i] != sc.sids[j] ) {
3950                         slap_insert_csn_sids( &sc, j, syncCookie->sids[i],
3951                                 &syncCookie->ctxcsn[i] );
3952                         if ( BER_BVISNULL( &first ) ||
3953                                 memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 ) {
3954                                 first = syncCookie->ctxcsn[i];
3955                         }
3956                         changed = 1;
3957                 }
3958         }
3959         /* Should never happen, ITS#5065 */
3960         if ( BER_BVISNULL( &first ) || !changed ) {
3961                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3962                 ber_bvarray_free( sc.ctxcsn );
3963                 ch_free( sc.sids );
3964                 return 0;
3965         }
3966         op->o_bd = si->si_wbe;
3967         slap_queue_csn( op, &first );
3968
3969         op->o_tag = LDAP_REQ_MODIFY;
3970
3971         cb.sc_response = null_callback;
3972         cb.sc_private = si;
3973
3974         op->o_callback = &cb;
3975         op->o_req_dn = si->si_contextdn;
3976         op->o_req_ndn = si->si_contextdn;
3977
3978         /* update contextCSN */
3979         op->o_dont_replicate = 1;
3980
3981         mod.sml_numvals = sc.numcsns;
3982         mod.sml_values = sc.ctxcsn;
3983
3984         op->orm_modlist = &mod;
3985         op->orm_no_opattrs = 1;
3986         rc = op->o_bd->be_modify( op, &rs_modify );
3987
3988         if ( rs_modify.sr_err == LDAP_NO_SUCH_OBJECT &&
3989                 SLAP_SYNC_SUBENTRY( op->o_bd )) {
3990                 const char      *text;
3991                 char txtbuf[SLAP_TEXT_BUFLEN];
3992                 size_t textlen = sizeof txtbuf;
3993                 Entry *e = slap_create_context_csn_entry( op->o_bd, NULL );
3994                 rs_reinit( &rs_modify, REP_RESULT );
3995                 rc = slap_mods2entry( &mod, &e, 0, 1, &text, txtbuf, textlen);
3996                 op->ora_e = e;
3997                 rc = op->o_bd->be_add( op, &rs_modify );
3998                 if ( e == op->ora_e )
3999                         be_entry_release_w( op, op->ora_e );
4000         }
4001
4002         op->orm_no_opattrs = 0;
4003         op->o_dont_replicate = 0;
4004
4005         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
4006                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
4007                 ber_bvarray_free( si->si_cookieState->cs_vals );
4008                 ch_free( si->si_cookieState->cs_sids );
4009                 si->si_cookieState->cs_vals = sc.ctxcsn;
4010                 si->si_cookieState->cs_sids = sc.sids;
4011                 si->si_cookieState->cs_num = sc.numcsns;
4012
4013                 /* Don't just dup the provider's cookie, recreate it */
4014                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
4015                 ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn, si->si_cookieState->cs_vals, NULL );
4016                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num * sizeof(int) );
4017                 for ( i=0; i<si->si_cookieState->cs_num; i++ )
4018                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
4019
4020                 si->si_cookieState->cs_age++;
4021                 si->si_cookieAge = si->si_cookieState->cs_age;
4022         } else {
4023                 Debug( LDAP_DEBUG_ANY,
4024                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
4025                         si->si_ridtxt, rs_modify.sr_err, 0 );
4026                 ch_free( sc.sids );
4027                 ber_bvarray_free( sc.ctxcsn );
4028         }
4029
4030 #ifdef CHECK_CSN
4031         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
4032                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
4033         }
4034 #endif
4035
4036         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
4037
4038         op->o_bd = be;
4039         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
4040         BER_BVZERO( &op->o_csn );
4041         if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
4042
4043         return rc;
4044 }
4045
4046 /* Compare the attribute from the old entry to the one in the new
4047  * entry. The Modifications from the new entry will either be left
4048  * in place, or changed to an Add or Delete as needed.
4049  */
4050 static void
4051 attr_cmp( Operation *op, Attribute *old, Attribute *new,
4052         Modifications ***mret, Modifications ***mcur )
4053 {
4054         int i, j;
4055         Modifications *mod, **modtail;
4056
4057         modtail = *mret;
4058
4059         if ( old ) {
4060                 int n, o, nn, no;
4061                 struct berval **adds, **dels;
4062                 /* count old and new */
4063                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
4064                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
4065
4066                 /* there MUST be both old and new values */
4067                 assert( o != 0 );
4068                 assert( n != 0 );
4069                 j = 0;
4070
4071                 adds = op->o_tmpalloc( sizeof(struct berval *) * n, op->o_tmpmemctx );
4072                 dels = op->o_tmpalloc( sizeof(struct berval *) * o, op->o_tmpmemctx );
4073
4074                 for ( i=0; i<o; i++ ) dels[i] = &old->a_vals[i];
4075                 for ( i=0; i<n; i++ ) adds[i] = &new->a_vals[i];
4076
4077                 nn = n; no = o;
4078
4079                 for ( i=0; i<o; i++ ) {
4080                         for ( j=0; j<n; j++ ) {
4081                                 if ( !adds[j] )
4082                                         continue;
4083                                 if ( bvmatch( dels[i], adds[j] ) ) {
4084                                         no--;
4085                                         nn--;
4086                                         adds[j] = NULL;
4087                                         dels[i] = NULL;
4088                                         break;
4089                                 }
4090                         }
4091                 }
4092
4093                 /* Don't delete/add an objectClass, always use the replace op.
4094                  * Modify would fail if provider has replaced entry with a new,
4095                  * and the new explicitly includes a superior of a class that was
4096                  * only included implicitly in the old entry.  Ref ITS#5517.
4097                  *
4098                  * Also use replace op if attr has no equality matching rule.
4099                  * (ITS#5781)
4100                  */
4101                 if ( ( nn || ( no > 0 && no < o ) ) &&
4102                         ( old->a_desc == slap_schema.si_ad_objectClass ||
4103                          !old->a_desc->ad_type->sat_equality ) )
4104                 {
4105                         no = o;
4106                 }
4107
4108                 i = j;
4109                 /* all old values were deleted, just use the replace op */
4110                 if ( no == o ) {
4111                         i = j-1;
4112                 } else if ( no ) {
4113                 /* delete some values */
4114                         mod = ch_malloc( sizeof( Modifications ) );
4115                         mod->sml_op = LDAP_MOD_DELETE;
4116                         mod->sml_flags = 0;
4117                         mod->sml_desc = old->a_desc;
4118                         mod->sml_type = mod->sml_desc->ad_cname;
4119                         mod->sml_numvals = no;
4120                         mod->sml_values = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
4121                         if ( old->a_vals != old->a_nvals ) {
4122                                 mod->sml_nvalues = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
4123                         } else {
4124                                 mod->sml_nvalues = NULL;
4125                         }
4126                         j = 0;
4127                         for ( i = 0; i < o; i++ ) {
4128                                 if ( !dels[i] ) continue;
4129                                 ber_dupbv( &mod->sml_values[j], &old->a_vals[i] );
4130                                 if ( mod->sml_nvalues ) {
4131                                         ber_dupbv( &mod->sml_nvalues[j], &old->a_nvals[i] );
4132                                 }
4133                                 j++;
4134                         }
4135                         BER_BVZERO( &mod->sml_values[j] );
4136                         if ( mod->sml_nvalues ) {
4137                                 BER_BVZERO( &mod->sml_nvalues[j] );
4138                         }
4139                         *modtail = mod;
4140                         modtail = &mod->sml_next;
4141                         i = j;
4142                 }
4143                 op->o_tmpfree( dels, op->o_tmpmemctx );
4144                 /* some values were added */
4145                 if ( nn && no < o ) {
4146                         mod = ch_malloc( sizeof( Modifications ) );
4147                         mod->sml_op = LDAP_MOD_ADD;
4148                         mod->sml_flags = 0;
4149                         mod->sml_desc = old->a_desc;
4150                         mod->sml_type = mod->sml_desc->ad_cname;
4151                         mod->sml_numvals = nn;
4152                         mod->sml_values = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
4153                         if ( old->a_vals != old->a_nvals ) {
4154                                 mod->sml_nvalues = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
4155                         } else {
4156                                 mod->sml_nvalues = NULL;
4157                         }
4158                         j = 0;
4159                         for ( i = 0; i < n; i++ ) {
4160                                 if ( !adds[i] ) continue;
4161                                 ber_dupbv( &mod->sml_values[j], &new->a_vals[i] );
4162                                 if ( mod->sml_nvalues ) {
4163                                         ber_dupbv( &mod->sml_nvalues[j], &new->a_nvals[i] );
4164                                 }
4165                                 j++;
4166                         }
4167                         BER_BVZERO( &mod->sml_values[j] );
4168                         if ( mod->sml_nvalues ) {
4169                                 BER_BVZERO( &mod->sml_nvalues[j] );
4170                         }
4171                         *modtail = mod;
4172                         modtail = &mod->sml_next;
4173                         i = j;
4174                 }
4175                 op->o_tmpfree( adds, op->o_tmpmemctx );
4176         } else {
4177                 /* new attr, just use the new mod */
4178                 i = 0;
4179                 j = 1;
4180         }
4181         /* advance to next element */
4182         mod = **mcur;
4183         if ( mod ) {
4184                 if ( i != j ) {
4185                         **mcur = mod->sml_next;
4186                         *modtail = mod;
4187                         modtail = &mod->sml_next;
4188                 } else {
4189                         *mcur = &mod->sml_next;
4190                 }
4191         }
4192         *mret = modtail;
4193 }
4194
4195 /* Generate a set of modifications to change the old entry into the
4196  * new one. On input ml is a list of modifications equivalent to
4197  * the new entry. It will be massaged and the result will be stored
4198  * in mods.
4199  */
4200 void syncrepl_diff_entry( Operation *op, Attribute *old, Attribute *new,
4201         Modifications **mods, Modifications **ml, int is_ctx)
4202 {
4203         Modifications **modtail = mods;
4204
4205         /* We assume that attributes are saved in the same order
4206          * in the remote and local databases. So if we walk through
4207          * the attributeDescriptions one by one they should match in
4208          * lock step. If not, look for an add or delete.
4209          */
4210         while ( old && new )
4211         {
4212                 /* If we've seen this before, use its mod now */
4213                 if ( new->a_flags & SLAP_ATTR_IXADD ) {
4214                         attr_cmp( op, NULL, new, &modtail, &ml );
4215                         new = new->a_next;
4216                         continue;
4217                 }
4218                 /* Skip contextCSN */
4219                 if ( is_ctx && old->a_desc ==
4220                         slap_schema.si_ad_contextCSN ) {
4221                         old = old->a_next;
4222                         continue;
4223                 }
4224
4225                 if ( old->a_desc != new->a_desc ) {
4226                         Modifications *mod;
4227                         Attribute *tmp;
4228
4229                         /* If it's just been re-added later,
4230                          * remember that we've seen it.
4231                          */
4232                         tmp = attr_find( new, old->a_desc );
4233                         if ( tmp ) {
4234                                 tmp->a_flags |= SLAP_ATTR_IXADD;
4235                         } else {
4236                                 /* If it's a new attribute, pull it in.
4237                                  */
4238                                 tmp = attr_find( old, new->a_desc );
4239                                 if ( !tmp ) {
4240                                         attr_cmp( op, NULL, new, &modtail, &ml );
4241                                         new = new->a_next;
4242                                         continue;
4243                                 }
4244                                 /* Delete old attr */
4245                                 mod = ch_malloc( sizeof( Modifications ) );
4246                                 mod->sml_op = LDAP_MOD_DELETE;
4247                                 mod->sml_flags = 0;
4248                                 mod->sml_desc = old->a_desc;
4249                                 mod->sml_type = mod->sml_desc->ad_cname;
4250                                 mod->sml_numvals = 0;
4251                                 mod->sml_values = NULL;
4252                                 mod->sml_nvalues = NULL;
4253                                 *modtail = mod;
4254                                 modtail = &mod->sml_next;
4255                         }
4256                         old = old->a_next;
4257                         continue;
4258                 }
4259                 /* kludge - always update modifiersName so that it
4260                  * stays co-located with the other mod opattrs. But only
4261                  * if we know there are other valid mods.
4262                  */
4263                 if ( *mods && ( old->a_desc == slap_schema.si_ad_modifiersName ||
4264                         old->a_desc == slap_schema.si_ad_modifyTimestamp ))
4265                         attr_cmp( op, NULL, new, &modtail, &ml );
4266                 else
4267                         attr_cmp( op, old, new, &modtail, &ml );
4268                 new = new->a_next;
4269                 old = old->a_next;
4270         }
4271         *modtail = *ml;
4272         *ml = NULL;
4273 }
4274
4275 static int
4276 dn_callback(
4277         Operation*      op,
4278         SlapReply*      rs )
4279 {
4280         dninfo *dni = op->o_callback->sc_private;
4281
4282         if ( rs->sr_type == REP_SEARCH ) {
4283                 if ( !BER_BVISNULL( &dni->dn ) ) {
4284                         Debug( LDAP_DEBUG_ANY,
4285                                 "dn_callback : consistency error - "
4286                                 "entryUUID is not unique\n", 0, 0, 0 );
4287                 } else {
4288                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
4289                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
4290                         /* If there is a new entry, see if it differs from the old.
4291                          * We compare the non-normalized values so that cosmetic changes
4292                          * in the provider are always propagated.
4293                          */
4294                         if ( dni->new_entry ) {
4295                                 Attribute *old, *new;
4296                                 struct berval old_rdn, new_rdn;
4297                                 struct berval old_p, new_p;
4298                                 int is_ctx, new_sup = 0;
4299
4300                                 /* If old entry is not a glue entry, make sure new entry
4301                                  * is actually newer than old entry
4302                                  */
4303                                 if ( !is_entry_glue( rs->sr_entry )) {
4304                                         old = attr_find( rs->sr_entry->e_attrs,
4305                                                 slap_schema.si_ad_entryCSN );
4306                                         new = attr_find( dni->new_entry->e_attrs,
4307                                                 slap_schema.si_ad_entryCSN );
4308                                         if ( new && old ) {
4309                                                 int rc;
4310                                                 ber_len_t len = old->a_vals[0].bv_len;
4311                                                 if ( len > new->a_vals[0].bv_len )
4312                                                         len = new->a_vals[0].bv_len;
4313                                                 rc = memcmp( old->a_vals[0].bv_val,
4314                                                         new->a_vals[0].bv_val, len );
4315                                                 if ( rc > 0 ) {
4316                                                         Debug( LDAP_DEBUG_SYNC,
4317                                                                 "dn_callback : new entry is older than ours "
4318                                                                 "%s ours %s, new %s\n",
4319                                                                 rs->sr_entry->e_name.bv_val,
4320                                                                 old->a_vals[0].bv_val,
4321                                                                 new->a_vals[0].bv_val );
4322                                                         return LDAP_SUCCESS;
4323                                                 } else if ( rc == 0 ) {
4324                                                         Debug( LDAP_DEBUG_SYNC,
4325                                                                 "dn_callback : entries have identical CSN "
4326                                                                 "%s %s\n",
4327                                                                 rs->sr_entry->e_name.bv_val,
4328                                                                 old->a_vals[0].bv_val, 0 );
4329                                                         return LDAP_SUCCESS;
4330                                                 }
4331                                         }
4332                                 }
4333
4334                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
4335                                         &op->o_bd->be_nsuffix[0] );
4336
4337                                 /* Did the DN change?
4338                                  * case changes in the parent are ignored,
4339                                  * we only want to know if the RDN was
4340                                  * actually changed.
4341                                  */
4342                                 dnRdn( &rs->sr_entry->e_name, &old_rdn );
4343                                 dnRdn( &dni->new_entry->e_name, &new_rdn );
4344                                 dnParent( &rs->sr_entry->e_nname, &old_p );
4345                                 dnParent( &dni->new_entry->e_nname, &new_p );
4346
4347                                 new_sup = !dn_match( &old_p, &new_p );
4348                                 if ( !dn_match( &old_rdn, &new_rdn ) || new_sup )
4349                                 {
4350                                         struct berval oldRDN, oldVal;
4351                                         AttributeDescription *ad = NULL;
4352                                         int oldpos, newpos;
4353                                         Attribute *a;
4354
4355                                         dni->renamed = 1;
4356                                         if ( new_sup )
4357                                                 dni->nnewSup = new_p;
4358
4359                                         /* See if the oldRDN was deleted */
4360                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
4361                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
4362                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
4363                                                 oldRDN.bv_val );
4364                                         oldRDN.bv_len -= oldVal.bv_len + 1;
4365                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
4366                                         dni->oldDesc = ad;
4367                                         for ( oldpos=0, a=rs->sr_entry->e_attrs;
4368                                                 a && a->a_desc != ad; oldpos++, a=a->a_next );
4369                                         /* a should not be NULL but apparently it happens.
4370                                          * ITS#7144
4371                                          */
4372                                         dni->oldNcount = a ? a->a_numvals : 0;
4373                                         for ( newpos=0, a=dni->new_entry->e_attrs;
4374                                                 a && a->a_desc != ad; newpos++, a=a->a_next );
4375                                         if ( !a || oldpos != newpos || attr_valfind( a,
4376                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
4377                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
4378                                                 SLAP_MR_VALUE_OF_SYNTAX,
4379                                                 &oldVal, NULL, op->o_tmpmemctx ) != LDAP_SUCCESS )
4380                                         {
4381                                                 dni->delOldRDN = 1;
4382                                         }
4383                                         /* Get the newRDN's desc */
4384                                         dnRdn( &dni->new_entry->e_nname, &oldRDN );
4385                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=');
4386                                         oldRDN.bv_len = oldVal.bv_val - oldRDN.bv_val;
4387                                         ad = NULL;
4388                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
4389                                         dni->newDesc = ad;
4390
4391                                         /* A ModDN has happened, but in Refresh mode other
4392                                          * changes may have occurred before we picked it up.
4393                                          * So fallthru to regular Modify processing.
4394                                          */
4395                                 }
4396
4397                                 syncrepl_diff_entry( op, rs->sr_entry->e_attrs,
4398                                         dni->new_entry->e_attrs, &dni->mods, dni->modlist,
4399                                         is_ctx );
4400                         }
4401                 }
4402         } else if ( rs->sr_type == REP_RESULT ) {
4403                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
4404                         Debug( LDAP_DEBUG_ANY,
4405                                 "dn_callback : consistency error - "
4406                                 "entryUUID is not unique\n", 0, 0, 0 );
4407                 }
4408         }
4409
4410         return LDAP_SUCCESS;
4411 }
4412
4413 static int
4414 nonpresent_callback(
4415         Operation*      op,
4416         SlapReply*      rs )
4417 {
4418         syncinfo_t *si = op->o_callback->sc_private;
4419         Attribute *a;
4420         int count = 0;
4421         char *present_uuid = NULL;
4422         struct nonpresent_entry *np_entry;
4423
4424         if ( rs->sr_type == REP_RESULT ) {
4425                 count = presentlist_free( si->si_presentlist );
4426                 si->si_presentlist = NULL;
4427
4428         } else if ( rs->sr_type == REP_SEARCH ) {
4429                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
4430                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
4431
4432                         if ( a ) {
4433                                 present_uuid = presentlist_find( si->si_presentlist, &a->a_nvals[0] );
4434                         }
4435
4436                         if ( LogTest( LDAP_DEBUG_SYNC ) ) {
4437                                 char buf[sizeof("rid=999 non")];
4438
4439                                 snprintf( buf, sizeof(buf), "%s %s", si->si_ridtxt,
4440                                         present_uuid ? "" : "non" );
4441
4442                                 Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %spresent UUID %s, dn %s\n",
4443                                         buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
4444                         }
4445
4446                         if ( a == NULL ) return 0;
4447                 }
4448
4449                 if ( present_uuid == NULL ) {
4450                         np_entry = (struct nonpresent_entry *)
4451                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
4452                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
4453                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
4454                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
4455
4456                 } else {
4457                         presentlist_delete( &si->si_presentlist, &a->a_nvals[0] );
4458                         ch_free( present_uuid );
4459                 }
4460         }
4461         return LDAP_SUCCESS;
4462 }
4463
4464 static int
4465 null_callback(
4466         Operation*      op,
4467         SlapReply*      rs )
4468 {
4469         if ( rs->sr_err != LDAP_SUCCESS &&
4470                 rs->sr_err != LDAP_REFERRAL &&
4471                 rs->sr_err != LDAP_ALREADY_EXISTS &&
4472                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
4473                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
4474         {
4475                 Debug( LDAP_DEBUG_ANY,
4476                         "null_callback : error code 0x%x\n",
4477                         rs->sr_err, 0, 0 );
4478         }
4479         return LDAP_SUCCESS;
4480 }
4481
4482 static struct berval *
4483 slap_uuidstr_from_normalized(
4484         struct berval* uuidstr,
4485         struct berval* normalized,
4486         void *ctx )
4487 {
4488 #if 0
4489         struct berval *new;
4490         unsigned char nibble;
4491         int i, d = 0;
4492
4493         if ( normalized == NULL ) return NULL;
4494         if ( normalized->bv_len != 16 ) return NULL;
4495
4496         if ( uuidstr ) {
4497                 new = uuidstr;
4498         } else {
4499                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
4500                 if ( new == NULL ) {
4501                         return NULL;
4502                 }
4503         }
4504
4505         new->bv_len = 36;
4506
4507         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
4508                 if ( new != uuidstr ) {
4509                         slap_sl_free( new, ctx );
4510                 }
4511                 return NULL;
4512         }
4513
4514         for ( i = 0; i < 16; i++ ) {
4515                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
4516                         new->bv_val[(i<<1)+d] = '-';
4517                         d += 1;
4518                 }
4519
4520                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
4521                 if ( nibble < 10 ) {
4522                         new->bv_val[(i<<1)+d] = nibble + '0';
4523                 } else {
4524                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
4525                 }
4526
4527                 nibble = (normalized->bv_val[i]) & 0xF;
4528                 if ( nibble < 10 ) {
4529                         new->bv_val[(i<<1)+d+1] = nibble + '0';
4530                 } else {
4531                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
4532                 }
4533         }
4534
4535         new->bv_val[new->bv_len] = '\0';
4536         return new;
4537 #endif
4538
4539         struct berval   *new;
4540         int             rc = 0;
4541
4542         if ( normalized == NULL ) return NULL;
4543         if ( normalized->bv_len != 16 ) return NULL;
4544
4545         if ( uuidstr ) {
4546                 new = uuidstr;
4547
4548         } else {
4549                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
4550                 if ( new == NULL ) {
4551                         return NULL;
4552                 }
4553         }
4554
4555         new->bv_len = 36;
4556
4557         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
4558                 rc = 1;
4559                 goto done;
4560         }
4561
4562         rc = lutil_uuidstr_from_normalized( normalized->bv_val,
4563                 normalized->bv_len, new->bv_val, new->bv_len + 1 );
4564
4565 done:;
4566         if ( rc == -1 ) {
4567                 if ( new != NULL ) {
4568                         if ( new->bv_val != NULL ) {
4569                                 slap_sl_free( new->bv_val, ctx );
4570                         }
4571
4572                         if ( new != uuidstr ) {
4573                                 slap_sl_free( new, ctx );
4574                         }
4575                 }
4576                 new = NULL;
4577
4578         } else {
4579                 new->bv_len = rc;
4580         }
4581
4582         return new;
4583 }
4584
4585 static int
4586 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
4587 {
4588 #ifdef HASHUUID
4589         return ( memcmp( v_uuid1, v_uuid2, UUIDLEN-2 ));
4590 #else
4591         return ( memcmp( v_uuid1, v_uuid2, UUIDLEN ));
4592 #endif
4593 }
4594
4595 void
4596 syncinfo_free( syncinfo_t *sie, int free_all )
4597 {
4598         syncinfo_t *si_next;
4599
4600         Debug( LDAP_DEBUG_TRACE, "syncinfo_free: %s\n",
4601                 sie->si_ridtxt, 0, 0 );
4602
4603         do {
4604                 si_next = sie->si_next;
4605
4606                 if ( sie->si_ld ) {
4607                         if ( sie->si_conn ) {
4608                                 connection_client_stop( sie->si_conn );
4609                                 sie->si_conn = NULL;
4610                         }
4611                         ldap_unbind_ext( sie->si_ld, NULL, NULL );
4612                 }
4613         
4614                 if ( sie->si_re ) {
4615                         struct re_s             *re = sie->si_re;
4616                         sie->si_re = NULL;
4617
4618                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4619                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
4620                                 ldap_pvt_runqueue_stoptask( &slapd_rq, re );
4621                         ldap_pvt_runqueue_remove( &slapd_rq, re );
4622                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4623                 }
4624
4625                 ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
4626
4627                 bindconf_free( &sie->si_bindconf );
4628
4629                 if ( sie->si_filterstr.bv_val ) {
4630                         ch_free( sie->si_filterstr.bv_val );
4631                 }
4632                 if ( sie->si_filter ) {
4633                         filter_free( sie->si_filter );
4634                 }
4635                 if ( sie->si_logfilterstr.bv_val ) {
4636                         ch_free( sie->si_logfilterstr.bv_val );
4637                 }
4638                 if ( sie->si_logfilter ) {
4639                         filter_free( sie->si_logfilter );
4640                 }
4641                 if ( sie->si_base.bv_val ) {
4642                         ch_free( sie->si_base.bv_val );
4643                 }
4644                 if ( sie->si_logbase.bv_val ) {
4645                         ch_free( sie->si_logbase.bv_val );
4646                 }
4647                 if ( sie->si_be && SLAP_SYNC_SUBENTRY( sie->si_be )) {
4648                         ch_free( sie->si_contextdn.bv_val );
4649                 }
4650                 if ( sie->si_attrs ) {
4651                         int i = 0;
4652                         while ( sie->si_attrs[i] != NULL ) {
4653                                 ch_free( sie->si_attrs[i] );
4654                                 i++;
4655                         }
4656                         ch_free( sie->si_attrs );
4657                 }
4658                 if ( sie->si_exattrs ) {
4659                         int i = 0;
4660                         while ( sie->si_exattrs[i] != NULL ) {
4661                                 ch_free( sie->si_exattrs[i] );
4662                                 i++;
4663                         }
4664                         ch_free( sie->si_exattrs );
4665                 }
4666                 if ( sie->si_anlist ) {
4667                         int i = 0;
4668                         while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
4669                                 ch_free( sie->si_anlist[i].an_name.bv_val );
4670                                 i++;
4671                         }
4672                         ch_free( sie->si_anlist );
4673                 }
4674                 if ( sie->si_exanlist ) {
4675                         int i = 0;
4676                         while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
4677                                 ch_free( sie->si_exanlist[i].an_name.bv_val );
4678                                 i++;
4679                         }
4680                         ch_free( sie->si_exanlist );
4681                 }
4682                 if ( sie->si_retryinterval ) {
4683                         ch_free( sie->si_retryinterval );
4684                 }
4685                 if ( sie->si_retrynum ) {
4686                         ch_free( sie->si_retrynum );
4687                 }
4688                 if ( sie->si_retrynum_init ) {
4689                         ch_free( sie->si_retrynum_init );
4690                 }
4691                 slap_sync_cookie_free( &sie->si_syncCookie, 0 );
4692                 if ( sie->si_presentlist ) {
4693                     presentlist_free( sie->si_presentlist );
4694                 }
4695                 while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
4696                         struct nonpresent_entry* npe;
4697                         npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
4698                         LDAP_LIST_REMOVE( npe, npe_link );
4699                         if ( npe->npe_name ) {
4700                                 if ( npe->npe_name->bv_val ) {
4701                                         ch_free( npe->npe_name->bv_val );
4702                                 }
4703                                 ch_free( npe->npe_name );
4704                         }
4705                         if ( npe->npe_nname ) {
4706                                 if ( npe->npe_nname->bv_val ) {
4707                                         ch_free( npe->npe_nname->bv_val );
4708                                 }
4709                                 ch_free( npe->npe_nname );
4710                         }
4711                         ch_free( npe );
4712                 }
4713                 if ( sie->si_cookieState ) {
4714                         sie->si_cookieState->cs_ref--;
4715                         if ( !sie->si_cookieState->cs_ref ) {
4716                                 ch_free( sie->si_cookieState->cs_sids );
4717                                 ber_bvarray_free( sie->si_cookieState->cs_vals );
4718                                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
4719                                 ch_free( sie->si_cookieState->cs_psids );
4720                                 ber_bvarray_free( sie->si_cookieState->cs_pvals );
4721                                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_pmutex );
4722                                 ch_free( sie->si_cookieState );
4723                         }
4724                 }
4725 #ifdef ENABLE_REWRITE
4726                 if ( sie->si_rewrite )
4727                         rewrite_info_delete( &sie->si_rewrite );
4728                 if ( sie->si_suffixm.bv_val )
4729                         ch_free( sie->si_suffixm.bv_val );
4730 #endif
4731                 ch_free( sie );
4732                 sie = si_next;
4733         } while ( free_all && si_next );
4734 }
4735
4736 #ifdef ENABLE_REWRITE
4737 static int
4738 config_suffixm( ConfigArgs *c, syncinfo_t *si )
4739 {
4740         char *argvEngine[] = { "rewriteEngine", "on", NULL };
4741         char *argvContext[] = { "rewriteContext", SUFFIXM_CTX, NULL };
4742         char *argvRule[] = { "rewriteRule", NULL, NULL, ":", NULL };
4743         char *vnc, *rnc;
4744         int rc;
4745
4746         if ( si->si_rewrite )
4747                 rewrite_info_delete( &si->si_rewrite );
4748         si->si_rewrite = rewrite_info_init( REWRITE_MODE_USE_DEFAULT );
4749
4750         rc = rewrite_parse( si->si_rewrite, c->fname, c->lineno, 2, argvEngine );
4751         if ( rc != LDAP_SUCCESS )
4752                 return rc;
4753
4754         rc = rewrite_parse( si->si_rewrite, c->fname, c->lineno, 2, argvContext );
4755         if ( rc != LDAP_SUCCESS )
4756                 return rc;
4757
4758         vnc = ch_malloc( si->si_base.bv_len + 6 );
4759         strcpy( vnc, "(.*)" );
4760         lutil_strcopy( lutil_strcopy( vnc+4, si->si_base.bv_val ), "$" );
4761         argvRule[1] = vnc;
4762
4763         rnc = ch_malloc( si->si_suffixm.bv_len + 3 );
4764         strcpy( rnc, "%1" );
4765         strcpy( rnc+2, si->si_suffixm.bv_val );
4766         argvRule[2] = rnc;
4767
4768         rc = rewrite_parse( si->si_rewrite, c->fname, c->lineno, 4, argvRule );
4769         ch_free( vnc );
4770         ch_free( rnc );
4771         return rc;
4772 }
4773 #endif
4774
4775 /* NOTE: used & documented in slapd.conf(5) */
4776 #define IDSTR                   "rid"
4777 #define PROVIDERSTR             "provider"
4778 #define SCHEMASTR               "schemachecking"
4779 #define FILTERSTR               "filter"
4780 #define SEARCHBASESTR           "searchbase"
4781 #define SCOPESTR                "scope"
4782 #define ATTRSONLYSTR            "attrsonly"
4783 #define ATTRSSTR                "attrs"
4784 #define TYPESTR                 "type"
4785 #define INTERVALSTR             "interval"
4786 #define RETRYSTR                "retry"
4787 #define SLIMITSTR               "sizelimit"
4788 #define TLIMITSTR               "timelimit"
4789 #define SYNCDATASTR             "syncdata"
4790 #define LOGBASESTR              "logbase"
4791 #define LOGFILTERSTR    "logfilter"
4792 #define SUFFIXMSTR              "suffixmassage"
4793 #define STRICT_REFRESH  "strictrefresh"
4794 #define LAZY_COMMIT             "lazycommit"
4795
4796 /* FIXME: undocumented */
4797 #define EXATTRSSTR              "exattrs"
4798 #define MANAGEDSAITSTR          "manageDSAit"
4799
4800 /* mandatory */
4801 enum {
4802         GOT_RID                 = 0x00000001U,
4803         GOT_PROVIDER            = 0x00000002U,
4804         GOT_SCHEMACHECKING      = 0x00000004U,
4805         GOT_FILTER              = 0x00000008U,
4806         GOT_SEARCHBASE          = 0x00000010U,
4807         GOT_SCOPE               = 0x00000020U,
4808         GOT_ATTRSONLY           = 0x00000040U,
4809         GOT_ATTRS               = 0x00000080U,
4810         GOT_TYPE                = 0x00000100U,
4811         GOT_INTERVAL            = 0x00000200U,
4812         GOT_RETRY               = 0x00000400U,
4813         GOT_SLIMIT              = 0x00000800U,
4814         GOT_TLIMIT              = 0x00001000U,
4815         GOT_SYNCDATA            = 0x00002000U,
4816         GOT_LOGBASE             = 0x00004000U,
4817         GOT_LOGFILTER           = 0x00008000U,
4818         GOT_EXATTRS             = 0x00010000U,
4819         GOT_MANAGEDSAIT         = 0x00020000U,
4820         GOT_BINDCONF            = 0x00040000U,
4821         GOT_SUFFIXM             = 0x00080000U,
4822
4823 /* check */
4824         GOT_REQUIRED            = (GOT_RID|GOT_PROVIDER|GOT_SEARCHBASE)
4825 };
4826
4827 static slap_verbmasks datamodes[] = {
4828         { BER_BVC("default"), SYNCDATA_DEFAULT },
4829         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
4830         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
4831         { BER_BVNULL, 0 }
4832 };
4833
4834 static int
4835 parse_syncrepl_retry(
4836         ConfigArgs      *c,
4837         char            *arg,
4838         syncinfo_t      *si )
4839 {
4840         char **retry_list;
4841         int j, k, n;
4842         int use_default = 0;
4843
4844         char *val = arg + STRLENOF( RETRYSTR "=" );
4845         if ( strcasecmp( val, "undefined" ) == 0 ) {
4846                 val = "3600 +";
4847                 use_default = 1;
4848         }
4849
4850         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
4851         retry_list[0] = NULL;
4852
4853         slap_str2clist( &retry_list, val, " ,\t" );
4854
4855         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
4856         n = k / 2;
4857         if ( k % 2 ) {
4858                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4859                         "Error: incomplete syncrepl retry list" );
4860                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4861                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
4862                         ch_free( retry_list[k] );
4863                 }
4864                 ch_free( retry_list );
4865                 return 1;
4866         }
4867         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
4868         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
4869         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
4870         for ( j = 0; j < n; j++ ) {
4871                 unsigned long   t;
4872                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
4873                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4874                                 "Error: invalid retry interval \"%s\" (#%d)",
4875                                 retry_list[j*2], j );
4876                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4877                         /* do some cleanup */
4878                         return 1;
4879                 }
4880                 si->si_retryinterval[j] = (time_t)t;
4881                 if ( *retry_list[j*2+1] == '+' ) {
4882                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
4883                         si->si_retrynum[j] = RETRYNUM_FOREVER;
4884                         j++;
4885                         break;
4886                 } else {
4887                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
4888                                         || si->si_retrynum_init[j] <= 0 )
4889                         {
4890                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4891                                         "Error: invalid initial retry number \"%s\" (#%d)",
4892                                         retry_list[j*2+1], j );
4893                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4894                                 /* do some cleanup */
4895                                 return 1;
4896                         }
4897                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
4898                                         || si->si_retrynum[j] <= 0 )
4899                         {
4900                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4901                                         "Error: invalid retry number \"%s\" (#%d)",
4902                                         retry_list[j*2+1], j );
4903                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4904                                 /* do some cleanup */
4905                                 return 1;
4906                         }
4907                 }
4908         }
4909         if ( j < 1 || si->si_retrynum_init[j-1] != RETRYNUM_FOREVER ) {
4910                 Debug( LDAP_DEBUG_CONFIG,
4911                         "%s: syncrepl will eventually stop retrying; the \"retry\" parameter should end with a '+'.\n",
4912                         c->log, 0, 0 );
4913         }
4914
4915         si->si_retrynum_init[j] = RETRYNUM_TAIL;
4916         si->si_retrynum[j] = RETRYNUM_TAIL;
4917         si->si_retryinterval[j] = 0;
4918         
4919         for ( k = 0; retry_list && retry_list[k]; k++ ) {
4920                 ch_free( retry_list[k] );
4921         }
4922         ch_free( retry_list );
4923         if ( !use_default ) {
4924                 si->si_got |= GOT_RETRY;
4925         }
4926
4927         return 0;
4928 }
4929
4930 static int
4931 parse_syncrepl_line(
4932         ConfigArgs      *c,
4933         syncinfo_t      *si )
4934 {
4935         int     i;
4936         char    *val;
4937
4938         for ( i = 1; i < c->argc; i++ ) {
4939                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
4940                                         STRLENOF( IDSTR "=" ) ) )
4941                 {
4942                         int tmp;
4943                         /* '\0' string terminator accounts for '=' */
4944                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
4945                         if ( lutil_atoi( &tmp, val ) != 0 ) {
4946                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4947                                         "Error: parse_syncrepl_line: "
4948                                         "unable to parse syncrepl id \"%s\"", val );
4949                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4950                                 return -1;
4951                         }
4952                         if ( tmp > SLAP_SYNC_RID_MAX || tmp < 0 ) {
4953                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4954                                         "Error: parse_syncrepl_line: "
4955                                         "syncrepl id %d is out of range [0..%d]", tmp, SLAP_SYNC_RID_MAX );
4956                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4957                                 return -1;
4958                         }
4959                         si->si_rid = tmp;
4960                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
4961                         si->si_got |= GOT_RID;
4962                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
4963                                         STRLENOF( PROVIDERSTR "=" ) ) )
4964                 {
4965                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
4966                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
4967 #ifdef HAVE_TLS
4968                         if ( ldap_is_ldaps_url( val ))
4969                                 si->si_bindconf.sb_tls_do_init = 1;
4970 #endif
4971                         si->si_got |= GOT_PROVIDER;
4972                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
4973                                         STRLENOF( SCHEMASTR "=" ) ) )
4974                 {
4975                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
4976                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
4977                                 si->si_schemachecking = 1;
4978                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
4979                                 si->si_schemachecking = 0;
4980                         } else {
4981                                 si->si_schemachecking = 1;
4982                         }
4983                         si->si_got |= GOT_SCHEMACHECKING;
4984                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
4985                                         STRLENOF( FILTERSTR "=" ) ) )
4986                 {
4987                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
4988                         if ( si->si_filterstr.bv_val )
4989                                 ch_free( si->si_filterstr.bv_val );
4990                         ber_str2bv( val, 0, 1, &si->si_filterstr );
4991                         si->si_got |= GOT_FILTER;
4992                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
4993                                         STRLENOF( LOGFILTERSTR "=" ) ) )
4994                 {
4995                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
4996                         if ( si->si_logfilterstr.bv_val )
4997                                 ch_free( si->si_logfilterstr.bv_val );
4998                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
4999                         si->si_got |= GOT_LOGFILTER;
5000                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
5001                                         STRLENOF( SEARCHBASESTR "=" ) ) )
5002                 {
5003                         struct berval   bv;
5004                         int             rc;
5005
5006                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
5007                         if ( si->si_base.bv_val ) {
5008                                 ch_free( si->si_base.bv_val );
5009                         }
5010                         ber_str2bv( val, 0, 0, &bv );
5011                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
5012                         if ( rc != LDAP_SUCCESS ) {
5013                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5014                                         "Invalid base DN \"%s\": %d (%s)",
5015                                         val, rc, ldap_err2string( rc ) );
5016                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5017                                 return -1;
5018                         }
5019                         si->si_got |= GOT_SEARCHBASE;
5020 #ifdef ENABLE_REWRITE
5021                 } else if ( !strncasecmp( c->argv[ i ], SUFFIXMSTR "=",
5022                                         STRLENOF( SUFFIXMSTR "=" ) ) )
5023                 {
5024                         struct berval   bv;
5025                         int             rc;
5026
5027                         val = c->argv[ i ] + STRLENOF( SUFFIXMSTR "=" );
5028                         if ( si->si_suffixm.bv_val ) {
5029                                 ch_free( si->si_suffixm.bv_val );
5030                         }
5031                         ber_str2bv( val, 0, 0, &bv );
5032                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_suffixm, NULL );
5033                         if ( rc != LDAP_SUCCESS ) {
5034                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5035                                         "Invalid massage DN \"%s\": %d (%s)",
5036                                         val, rc, ldap_err2string( rc ) );
5037                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5038                                 return -1;
5039                         }
5040                         if ( !be_issubordinate( c->be, &si->si_suffixm )) {
5041                                 ch_free( si->si_suffixm.bv_val );
5042                                 BER_BVZERO( &si->si_suffixm );
5043                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5044                                         "Massage DN \"%s\" is not within the database naming context",
5045                                         val );
5046                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5047                                 return -1;
5048                         }
5049                         si->si_got |= GOT_SUFFIXM;
5050 #endif
5051                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
5052                                         STRLENOF( LOGBASESTR "=" ) ) )
5053                 {
5054                         struct berval   bv;
5055                         int             rc;
5056
5057                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
5058                         if ( si->si_logbase.bv_val ) {
5059                                 ch_free( si->si_logbase.bv_val );
5060                         }
5061                         ber_str2bv( val, 0, 0, &bv );
5062                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
5063                         if ( rc != LDAP_SUCCESS ) {
5064                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5065                                         "Invalid logbase DN \"%s\": %d (%s)",
5066                                         val, rc, ldap_err2string( rc ) );
5067                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5068                                 return -1;
5069                         }
5070                         si->si_got |= GOT_LOGBASE;
5071                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
5072                                         STRLENOF( SCOPESTR "=" ) ) )
5073                 {
5074                         int j;
5075                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
5076                         j = ldap_pvt_str2scope( val );
5077                         if ( j < 0 ) {
5078                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5079                                         "Error: parse_syncrepl_line: "
5080                                         "unknown scope \"%s\"", val);
5081                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5082                                 return -1;
5083                         }
5084                         si->si_scope = j;
5085                         si->si_got |= GOT_SCOPE;
5086                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
5087                                         STRLENOF( ATTRSONLYSTR ) ) )
5088                 {
5089                         si->si_attrsonly = 1;
5090                         si->si_got |= GOT_ATTRSONLY;
5091                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
5092                                         STRLENOF( ATTRSSTR "=" ) ) )
5093                 {
5094                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
5095                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
5096                                 char *attr_fname;
5097                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
5098                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
5099                                 if ( si->si_anlist == NULL ) {
5100                                         ch_free( attr_fname );
5101                                         return -1;
5102                                 }
5103                                 si->si_anfile = attr_fname;
5104                         } else {
5105                                 char *str, *s, *next;
5106                                 const char *delimstr = " ,\t";
5107                                 str = ch_strdup( val );
5108                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
5109                                                 s != NULL;
5110                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
5111                                 {
5112                                         if ( strlen(s) == 1 && *s == '*' ) {
5113                                                 si->si_allattrs = 1;
5114                                                 val[ s - str ] = delimstr[0];
5115                                         }
5116                                         if ( strlen(s) == 1 && *s == '+' ) {
5117                                                 si->si_allopattrs = 1;
5118                                                 val [ s - str ] = delimstr[0];
5119                                         }
5120                                 }
5121                                 ch_free( str );
5122                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
5123                                 if ( si->si_anlist == NULL ) {
5124                                         return -1;
5125                                 }
5126                         }
5127                         si->si_got |= GOT_ATTRS;
5128                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
5129                                         STRLENOF( EXATTRSSTR "=" ) ) )
5130                 {
5131                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
5132                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
5133                                 char *attr_fname;
5134                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
5135                                 si->si_exanlist = file2anlist(
5136                                         si->si_exanlist, attr_fname, " ,\t" );
5137                                 if ( si->si_exanlist == NULL ) {
5138                                         ch_free( attr_fname );
5139                                         return -1;
5140                                 }
5141                                 ch_free( attr_fname );
5142                         } else {
5143                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
5144                                 if ( si->si_exanlist == NULL ) {
5145                                         return -1;
5146                                 }
5147                         }
5148                         si->si_got |= GOT_EXATTRS;
5149                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
5150                                         STRLENOF( TYPESTR "=" ) ) )
5151                 {
5152                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
5153                         if ( !strncasecmp( val, "refreshOnly",
5154                                                 STRLENOF("refreshOnly") ) )
5155                         {
5156                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
5157                         } else if ( !strncasecmp( val, "refreshAndPersist",
5158                                                 STRLENOF("refreshAndPersist") ) )
5159                         {
5160                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
5161                                 si->si_interval = 60;
5162                         } else {
5163                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5164                                         "Error: parse_syncrepl_line: "
5165                                         "unknown sync type \"%s\"", val);
5166                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5167                                 return -1;
5168                         }
5169                         si->si_got |= GOT_TYPE;
5170                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
5171                                         STRLENOF( INTERVALSTR "=" ) ) )
5172                 {
5173                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
5174                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
5175                                 si->si_interval = 0;
5176                         } else if ( strchr( val, ':' ) != NULL ) {
5177                                 char *next, *ptr = val;
5178                                 int dd, hh, mm, ss;
5179
5180                                 dd = strtol( ptr, &next, 10 );
5181                                 if ( next == ptr || next[0] != ':' || dd < 0 ) {
5182                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5183                                                 "Error: parse_syncrepl_line: "
5184                                                 "invalid interval \"%s\", unable to parse days", val );
5185                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5186                                         return -1;
5187                                 }
5188                                 ptr = next + 1;
5189                                 hh = strtol( ptr, &next, 10 );
5190                                 if ( next == ptr || next[0] != ':' || hh < 0 || hh > 24 ) {
5191                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5192                                                 "Error: parse_syncrepl_line: "
5193                                                 "invalid interval \"%s\", unable to parse hours", val );
5194                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5195                                         return -1;
5196                                 }
5197                                 ptr = next + 1;
5198                                 mm = strtol( ptr, &next, 10 );
5199                                 if ( next == ptr || next[0] != ':' || mm < 0 || mm > 60 ) {
5200                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5201                                                 "Error: parse_syncrepl_line: "
5202                                                 "invalid interval \"%s\", unable to parse minutes", val );
5203                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5204                                         return -1;
5205                                 }
5206                                 ptr = next + 1;
5207                                 ss = strtol( ptr, &next, 10 );
5208                                 if ( next == ptr || next[0] != '\0' || ss < 0 || ss > 60 ) {
5209                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5210                                                 "Error: parse_syncrepl_line: "
5211                                                 "invalid interval \"%s\", unable to parse seconds", val );
5212                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5213                                         return -1;
5214                                 }
5215                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
5216                         } else {
5217                                 unsigned long   t;
5218
5219                                 if ( lutil_parse_time( val, &t ) != 0 ) {
5220                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5221                                                 "Error: parse_syncrepl_line: "
5222                                                 "invalid interval \"%s\"", val );
5223                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5224                                         return -1;
5225                                 }
5226                                 si->si_interval = (time_t)t;
5227                         }
5228                         if ( si->si_interval < 0 ) {
5229                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5230                                         "Error: parse_syncrepl_line: "
5231                                         "invalid interval \"%ld\"",
5232                                         (long) si->si_interval);
5233                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5234                                 return -1;
5235                         }
5236                         si->si_got |= GOT_INTERVAL;
5237                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
5238                                         STRLENOF( RETRYSTR "=" ) ) )
5239                 {
5240                         if ( parse_syncrepl_retry( c, c->argv[ i ], si ) ) {
5241                                 return 1;
5242                         }
5243                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
5244                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
5245                 {
5246                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
5247                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
5248                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
5249                         {
5250                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5251                                         "invalid manageDSAit value \"%s\".\n",
5252                                         val );
5253                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5254                                 return 1;
5255                         }
5256                         si->si_got |= GOT_MANAGEDSAIT;
5257                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
5258                                         STRLENOF( SLIMITSTR "=") ) )
5259                 {
5260                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
5261                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
5262                                 si->si_slimit = 0;
5263
5264                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
5265                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5266                                         "invalid size limit value \"%s\".\n",
5267                                         val );
5268                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5269                                 return 1;
5270                         }
5271                         si->si_got |= GOT_SLIMIT;
5272                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
5273                                         STRLENOF( TLIMITSTR "=" ) ) )
5274                 {
5275                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
5276                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
5277                                 si->si_tlimit = 0;
5278
5279                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
5280                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5281                                         "invalid time limit value \"%s\".\n",
5282                                         val );
5283                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5284                                 return 1;
5285                         }
5286                         si->si_got |= GOT_TLIMIT;
5287                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
5288                                         STRLENOF( SYNCDATASTR "=" ) ) )
5289                 {
5290                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
5291                         si->si_syncdata = verb_to_mask( val, datamodes );
5292                         si->si_got |= GOT_SYNCDATA;
5293                 } else if ( !strncasecmp( c->argv[ i ], STRICT_REFRESH,
5294                                         STRLENOF( STRICT_REFRESH ) ) )
5295                 {
5296                         si->si_strict_refresh = 1;
5297                 } else if ( !strncasecmp( c->argv[ i ], LAZY_COMMIT,
5298                                         STRLENOF( LAZY_COMMIT ) ) )
5299                 {
5300                         si->si_lazyCommit = 1;
5301                 } else if ( !bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
5302                         si->si_got |= GOT_BINDCONF;
5303                 } else {
5304                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5305                                 "Error: parse_syncrepl_line: "
5306                                 "unable to parse \"%s\"\n", c->argv[ i ] );
5307                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5308                         return -1;
5309                 }
5310         }
5311
5312         if ( ( si->si_got & GOT_REQUIRED ) != GOT_REQUIRED ) {
5313                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5314                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
5315                         si->si_got & GOT_RID ? "" : " "IDSTR,
5316                         si->si_got & GOT_PROVIDER ? "" : " "PROVIDERSTR,
5317                         si->si_got & GOT_SEARCHBASE ? "" : " "SEARCHBASESTR );
5318                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5319                 return -1;
5320         }
5321
5322         if ( !be_issubordinate( c->be, &si->si_base ) && !( si->si_got & GOT_SUFFIXM )) {
5323                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
5324                         "Base DN \"%s\" is not within the database naming context",
5325                         si->si_base.bv_val );
5326                 ch_free( si->si_base.bv_val );
5327                 BER_BVZERO( &si->si_base );
5328                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5329                 return -1;
5330         }
5331
5332 #ifdef ENABLE_REWRITE
5333         if ( si->si_got & GOT_SUFFIXM ) {
5334                 if (config_suffixm( c, si )) {
5335                         ch_free( si->si_suffixm.bv_val );
5336                         BER_BVZERO( &si->si_suffixm );
5337                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5338                                 "Error configuring rewrite engine" );
5339                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
5340                         return -1;
5341                 }
5342         }
5343 #endif
5344
5345         if ( !( si->si_got & GOT_RETRY ) ) {
5346                 Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": no retry defined, using default\n", 
5347                         si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", 0 );
5348                 if ( si->si_retryinterval == NULL ) {
5349                         if ( parse_syncrepl_retry( c, "retry=undefined", si ) ) {
5350                                 return 1;
5351                         }
5352                 }
5353         }
5354
5355         si->si_filter = str2filter( si->si_filterstr.bv_val );
5356         if ( si->si_filter == NULL ) {
5357                 Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": unable to parse filter=\"%s\"\n", 
5358                         si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", si->si_filterstr.bv_val );
5359                 return 1;
5360         }
5361
5362         if ( si->si_got & GOT_LOGFILTER ) {
5363                 si->si_logfilter = str2filter( si->si_logfilterstr.bv_val );
5364                 if ( si->si_logfilter == NULL ) {
5365                         Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": unable to parse logfilter=\"%s\"\n", 
5366                                 si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", si->si_logfilterstr.bv_val );
5367                         return 1;
5368                 }
5369         }
5370
5371         return 0;
5372 }
5373
5374 static int
5375 add_syncrepl(
5376         ConfigArgs *c )
5377 {
5378         syncinfo_t *si;
5379         int     rc = 0;
5380
5381         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
5382                 snprintf( c->cr_msg, sizeof(c->cr_msg), "database %s does not support "
5383                         "operations required for syncrepl", c->be->be_type );
5384                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
5385                 return 1;
5386         }
5387         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
5388                 strcpy( c->cr_msg, "rootDN must be defined before syncrepl may be used" );
5389                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
5390                 return 1;
5391         }
5392         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
5393
5394         if ( si == NULL ) {
5395                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
5396                 return 1;
5397         }
5398
5399         si->si_bindconf.sb_tls = SB_TLS_OFF;
5400         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
5401         si->si_schemachecking = 0;
5402         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
5403                 &si->si_filterstr );
5404         si->si_base.bv_val = NULL;
5405         si->si_scope = LDAP_SCOPE_SUBTREE;
5406         si->si_attrsonly = 0;
5407         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
5408         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
5409         si->si_attrs = NULL;
5410         si->si_allattrs = 0;
5411         si->si_allopattrs = 0;
5412         si->si_exattrs = NULL;
5413         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
5414         si->si_interval = 86400;
5415         si->si_retryinterval = NULL;
5416         si->si_retrynum_init = NULL;
5417         si->si_retrynum = NULL;
5418         si->si_manageDSAit = 0;
5419         si->si_tlimit = 0;
5420         si->si_slimit = 0;
5421
5422         si->si_presentlist = NULL;
5423         LDAP_LIST_INIT( &si->si_nonpresentlist );
5424         ldap_pvt_thread_mutex_init( &si->si_mutex );
5425
5426         rc = parse_syncrepl_line( c, si );
5427
5428         if ( rc == 0 ) {
5429                 LDAPURLDesc *lud;
5430
5431                 /* Must be LDAPv3 because we need controls */
5432                 switch ( si->si_bindconf.sb_version ) {
5433                 case 0:
5434                         /* not explicitly set */
5435                         si->si_bindconf.sb_version = LDAP_VERSION3;
5436                         break;
5437                 case 3:
5438                         /* explicitly set */
5439                         break;
5440                 default:
5441                         Debug( LDAP_DEBUG_ANY,
5442                                 "version %d incompatible with syncrepl\n",
5443                                 si->si_bindconf.sb_version, 0, 0 );
5444                         syncinfo_free( si, 0 ); 
5445                         return 1;
5446                 }
5447
5448                 if ( ldap_url_parse( si->si_bindconf.sb_uri.bv_val, &lud )) {
5449                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
5450                                 "<%s> invalid URL", c->argv[0] );
5451                         Debug( LDAP_DEBUG_ANY, "%s: %s %s\n",
5452                                 c->log, c->cr_msg, si->si_bindconf.sb_uri.bv_val );
5453                         return 1;
5454                 }
5455
5456                 si->si_be = c->be;
5457                 if ( slapMode & SLAP_SERVER_MODE ) {
5458                         int isMe = 0;
5459                         /* check if consumer points to current server and database.
5460                          * If so, ignore this configuration.
5461                          */
5462                         if ( !SLAP_DBHIDDEN( c->be ) ) {
5463                                 int i;
5464                                 /* if searchbase doesn't match current DB suffix,
5465                                  * assume it's different
5466                                  */
5467                                 for ( i=0; !BER_BVISNULL( &c->be->be_nsuffix[i] ); i++ ) {
5468                                         if ( bvmatch( &si->si_base, &c->be->be_nsuffix[i] )) {
5469                                                 isMe = 1;
5470                                                 break;
5471                                         }
5472                                 }
5473                                 /* if searchbase matches, see if URLs match */
5474                                 if ( isMe && config_check_my_url( si->si_bindconf.sb_uri.bv_val,
5475                                                 lud ) == NULL )
5476                                         isMe = 0;
5477                         }
5478
5479                         if ( !isMe ) {
5480                                 init_syncrepl( si );
5481                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
5482                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
5483                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
5484                                         si->si_ridtxt );
5485                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
5486                                 if ( si->si_re )
5487                                         rc = config_sync_shadow( c ) ? -1 : 0;
5488                                 else
5489                                         rc = -1;
5490                         }
5491                 } else {
5492                         /* mirrormode still needs to see this flag in tool mode */
5493                         rc = config_sync_shadow( c ) ? -1 : 0;
5494                 }
5495                 ldap_free_urldesc( lud );
5496         }
5497
5498 #ifdef HAVE_TLS
5499         /* Use main slapd defaults */
5500         bindconf_tls_defaults( &si->si_bindconf );
5501 #endif
5502         if ( rc < 0 ) {
5503                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
5504                 syncinfo_free( si, 0 ); 
5505                 return 1;
5506         } else {
5507                 Debug( LDAP_DEBUG_CONFIG,
5508                         "Config: ** successfully added syncrepl %s \"%s\"\n",
5509                         si->si_ridtxt,
5510                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
5511                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0 );
5512                 if ( c->be->be_syncinfo ) {
5513                         syncinfo_t *sip;
5514
5515                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
5516
5517                         /* add new syncrepl to end of list (same order as when deleting) */
5518                         for ( sip = c->be->be_syncinfo; sip->si_next; sip = sip->si_next );
5519                         sip->si_next = si;
5520                 } else {
5521                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
5522                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
5523                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_pmutex );
5524
5525                         c->be->be_syncinfo = si;
5526                 }
5527                 si->si_cookieState->cs_ref++;
5528
5529                 si->si_next = NULL;
5530
5531                 return 0;
5532         }
5533 }
5534
5535 static void
5536 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
5537 {
5538         struct berval bc, uri, bs;
5539         char buf[BUFSIZ*2], *ptr;
5540         ber_len_t len;
5541         int i;
5542 #       define WHATSLEFT        ((ber_len_t) (&buf[sizeof( buf )] - ptr))
5543
5544         BER_BVZERO( bv );
5545
5546         /* temporarily inhibit bindconf from printing URI */
5547         uri = si->si_bindconf.sb_uri;
5548         BER_BVZERO( &si->si_bindconf.sb_uri );
5549         si->si_bindconf.sb_version = 0;
5550         bindconf_unparse( &si->si_bindconf, &bc );
5551         si->si_bindconf.sb_uri = uri;
5552         si->si_bindconf.sb_version = LDAP_VERSION3;
5553
5554         ptr = buf;
5555         assert( si->si_rid >= 0 && si->si_rid <= SLAP_SYNC_RID_MAX );
5556         len = snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
5557                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
5558         if ( len >= sizeof( buf ) ) return;
5559         ptr += len;
5560         if ( !BER_BVISNULL( &bc ) ) {
5561                 if ( WHATSLEFT <= bc.bv_len ) {
5562                         free( bc.bv_val );
5563                         return;
5564                 }
5565                 ptr = lutil_strcopy( ptr, bc.bv_val );
5566                 free( bc.bv_val );
5567         }
5568         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
5569                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
5570                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
5571                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
5572                 *ptr++ = '"';
5573         }
5574         if ( !BER_BVISNULL( &si->si_base ) ) {
5575                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
5576                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
5577                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
5578                 *ptr++ = '"';
5579         }
5580 #ifdef ENABLE_REWRITE
5581         if ( !BER_BVISNULL( &si->si_suffixm ) ) {
5582                 if ( WHATSLEFT <= STRLENOF( " " SUFFIXMSTR "=\"" "\"" ) + si->si_suffixm.bv_len ) return;
5583                 ptr = lutil_strcopy( ptr, " " SUFFIXMSTR "=\"" );
5584                 ptr = lutil_strcopy( ptr, si->si_suffixm.bv_val );
5585                 *ptr++ = '"';
5586         }
5587 #endif
5588         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
5589                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
5590                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
5591                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
5592                 *ptr++ = '"';
5593         }
5594         if ( !BER_BVISNULL( &si->si_logbase ) ) {
5595                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
5596                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
5597                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
5598                 *ptr++ = '"';
5599         }
5600         if ( ldap_pvt_scope2bv( si->si_scope, &bs ) == LDAP_SUCCESS ) {
5601                 if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + bs.bv_len ) return;
5602                 ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
5603                 ptr = lutil_strcopy( ptr, bs.bv_val );
5604         }
5605         if ( si->si_attrsonly ) {
5606                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
5607                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
5608         }
5609         if ( si->si_anfile ) {
5610                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
5611                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
5612                 ptr = lutil_strcopy( ptr, si->si_anfile );
5613                 *ptr++ = '"';
5614         } else if ( si->si_allattrs || si->si_allopattrs ||
5615                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
5616         {
5617                 char *old;
5618
5619                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
5620                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
5621                 old = ptr;
5622                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
5623                 if ( ptr == NULL ) return;
5624                 if ( si->si_allattrs ) {
5625                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
5626                         if ( old != ptr ) *ptr++ = ',';
5627                         *ptr++ = '*';
5628                 }
5629                 if ( si->si_allopattrs ) {
5630                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
5631                         if ( old != ptr ) *ptr++ = ',';
5632                         *ptr++ = '+';
5633                 }
5634                 *ptr++ = '"';
5635         }
5636         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
5637                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
5638                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
5639                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
5640                 if ( ptr == NULL ) return;
5641         }
5642         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
5643         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
5644         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
5645         
5646         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
5647         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
5648         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
5649                 "refreshAndPersist" : "refreshOnly" );
5650
5651         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
5652                 int dd, hh, mm, ss;
5653
5654                 dd = si->si_interval;
5655                 ss = dd % 60;
5656                 dd /= 60;
5657                 mm = dd % 60;
5658                 dd /= 60;
5659                 hh = dd % 24;
5660                 dd /= 24;
5661                 len = snprintf( ptr, WHATSLEFT, " %s=%02d:%02d:%02d:%02d",
5662                         INTERVALSTR, dd, hh, mm, ss );
5663                 if ( len >= WHATSLEFT ) return;
5664                 ptr += len;
5665         }
5666
5667         if ( si->si_got & GOT_RETRY ) {
5668                 const char *space = "";
5669                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
5670                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
5671                 for (i=0; si->si_retryinterval[i]; i++) {
5672                         len = snprintf( ptr, WHATSLEFT, "%s%ld ", space,
5673                                 (long) si->si_retryinterval[i] );
5674                         space = " ";
5675                         if ( WHATSLEFT - 1 <= len ) return;
5676                         ptr += len;
5677                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
5678                                 *ptr++ = '+';
5679                         else {
5680                                 len = snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
5681                                 if ( WHATSLEFT <= len ) return;
5682                                 ptr += len;
5683                         }
5684                 }
5685                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
5686                 *ptr++ = '"';
5687         } else {
5688                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=undefined" );
5689         }
5690
5691         if ( si->si_slimit ) {
5692                 len = snprintf( ptr, WHATSLEFT, " " SLIMITSTR "=%d", si->si_slimit );
5693                 if ( WHATSLEFT <= len ) return;
5694                 ptr += len;
5695         }
5696
5697         if ( si->si_tlimit ) {
5698                 len = snprintf( ptr, WHATSLEFT, " " TLIMITSTR "=%d", si->si_tlimit );
5699                 if ( WHATSLEFT <= len ) return;
5700                 ptr += len;
5701         }
5702
5703         if ( si->si_syncdata ) {
5704                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
5705                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
5706                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
5707                         ptr = lutil_strcopy( ptr, bc.bv_val );
5708                 }
5709         }
5710
5711         if ( si->si_lazyCommit ) {
5712                 ptr = lutil_strcopy( ptr, " " LAZY_COMMIT );
5713         }
5714
5715         bc.bv_len = ptr - buf;
5716         bc.bv_val = buf;
5717         ber_dupbv( bv, &bc );
5718 }
5719
5720 int
5721 syncrepl_config( ConfigArgs *c )
5722 {
5723         if (c->op == SLAP_CONFIG_EMIT) {
5724                 if ( c->be->be_syncinfo ) {
5725                         struct berval bv;
5726                         syncinfo_t *si;
5727
5728                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
5729                                 syncrepl_unparse( si, &bv ); 
5730                                 ber_bvarray_add( &c->rvalue_vals, &bv );
5731                         }
5732                         return 0;
5733                 }
5734                 return 1;
5735         } else if ( c->op == LDAP_MOD_DELETE ) {
5736                 int isrunning = 0;
5737                 if ( c->be->be_syncinfo ) {
5738                         syncinfo_t *si, **sip;
5739                         int i;
5740
5741                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
5742                                 si = *sip;
5743                                 if ( c->valx == -1 || i == c->valx ) {
5744                                         *sip = si->si_next;
5745                                         si->si_ctype = -1;
5746                                         si->si_next = NULL;
5747                                         /* If the task is currently active, we have to leave
5748                                          * it running. It will exit on its own. This will only
5749                                          * happen when running on the cn=config DB.
5750                                          */
5751                                         if ( si->si_re ) {
5752                                                 if ( si->si_be == c->be || ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
5753                                                         isrunning = 1;
5754                                                 } else {
5755                                                         /* There is no active thread, but we must still
5756                                                          * ensure that no thread is (or will be) queued
5757                                                          * while we removes the task.
5758                                                          */
5759                                                         struct re_s *re = si->si_re;
5760                                                         si->si_re = NULL;
5761
5762                                                         if ( si->si_conn ) {
5763                                                                 connection_client_stop( si->si_conn );
5764                                                                 si->si_conn = NULL;
5765                                                         }
5766
5767                                                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
5768                                                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) ) {
5769                                                                 ldap_pvt_runqueue_stoptask( &slapd_rq, re );
5770                                                                 isrunning = 1;
5771                                                         }
5772                                                         if ( ldap_pvt_thread_pool_retract( &connection_pool,
5773                                                                         re->routine, re ) > 0 )
5774                                                                 isrunning = 0;
5775
5776                                                         ldap_pvt_runqueue_remove( &slapd_rq, re );
5777                                                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
5778
5779                                                         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
5780                                                 }
5781                                         }
5782                                         if ( !isrunning ) {
5783                                                 syncinfo_free( si, 0 );
5784                                         }
5785                                         if ( i == c->valx )
5786                                                 break;
5787                                 } else {
5788                                         sip = &si->si_next;
5789                                 }
5790                         }
5791                 }
5792                 if ( !c->be->be_syncinfo ) {
5793                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_SHADOW_MASK;
5794                 }
5795                 return 0;
5796         }
5797         if ( SLAP_SLURP_SHADOW( c->be ) ) {
5798                 Debug(LDAP_DEBUG_ANY, "%s: "
5799                         "syncrepl: database already shadowed.\n",
5800                         c->log, 0, 0);
5801                 return(1);
5802         } else {
5803                 return add_syncrepl( c );
5804         }
5805 }