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