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