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