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