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