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