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