]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
ITS#6335
[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, freeinfo = 0;
1260         Backend *be;
1261
1262         if ( si == NULL )
1263                 return NULL;
1264         if ( slapd_shutdown )
1265                 return NULL;
1266
1267         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl %s\n", si->si_ridtxt, 0, 0 );
1268
1269         /* Don't get stuck here while a pause is initiated */
1270         while ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
1271                 if ( slapd_shutdown )
1272                         return NULL;
1273                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1274                         ldap_pvt_thread_yield();
1275         }
1276
1277         if ( si->si_ctype < 1 ) {
1278                 goto deleted;
1279         }
1280
1281         switch( abs( si->si_type ) ) {
1282         case LDAP_SYNC_REFRESH_ONLY:
1283         case LDAP_SYNC_REFRESH_AND_PERSIST:
1284                 break;
1285         default:
1286                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1287                 return NULL;
1288         }
1289
1290         if ( slapd_shutdown ) {
1291                 if ( si->si_ld ) {
1292                         if ( si->si_conn ) {
1293                                 connection_client_stop( si->si_conn );
1294                                 si->si_conn = NULL;
1295                         }
1296                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1297                         si->si_ld = NULL;
1298                 }
1299                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1300                 return NULL;
1301         }
1302
1303         connection_fake_init( &conn, &opbuf, ctx );
1304         op = &opbuf.ob_op;
1305
1306         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1307         be = si->si_be;
1308
1309         /* Coordinate contextCSN updates with any syncprov overlays
1310          * in use. This may be complicated by the use of the glue
1311          * overlay.
1312          *
1313          * Typically there is a single syncprov mastering the entire
1314          * glued tree. In that case, our contextCSN updates should
1315          * go to the master DB. But if there is no syncprov on the
1316          * master DB, then nothing special is needed here.
1317          *
1318          * Alternatively, there may be individual syncprov overlays
1319          * on each glued branch. In that case, each syncprov only
1320          * knows about changes within its own branch. And so our
1321          * contextCSN updates should only go to the local DB.
1322          */
1323         if ( !si->si_wbe ) {
1324                 if ( SLAP_GLUE_SUBORDINATE( be ) && !overlay_is_inst( be, "syncprov" )) {
1325                         BackendDB * top_be = select_backend( &be->be_nsuffix[0], 1 );
1326                         if ( overlay_is_inst( top_be, "syncprov" ))
1327                                 si->si_wbe = select_backend( &be->be_nsuffix[0], 1 );
1328                         else
1329                                 si->si_wbe = be;
1330                 } else {
1331                         si->si_wbe = be;
1332                 }
1333         }
1334         if ( !si->si_schemachecking )
1335                 op->o_no_schema_check = 1;
1336
1337         /* Establish session, do search */
1338         if ( !si->si_ld ) {
1339                 si->si_refreshDelete = 0;
1340                 si->si_refreshPresent = 0;
1341
1342                 /* use main DB when retrieving contextCSN */
1343                 op->o_bd = si->si_wbe;
1344                 op->o_dn = op->o_bd->be_rootdn;
1345                 op->o_ndn = op->o_bd->be_rootndn;
1346                 rc = do_syncrep1( op, si );
1347         }
1348
1349 reload:
1350         /* Process results */
1351         if ( rc == LDAP_SUCCESS ) {
1352                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1353
1354                 /* use current DB */
1355                 op->o_bd = be;
1356                 op->o_dn = op->o_bd->be_rootdn;
1357                 op->o_ndn = op->o_bd->be_rootndn;
1358                 rc = do_syncrep2( op, si );
1359                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1360                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1361                         goto reload;
1362                 }
1363
1364 deleted:
1365                 /* We got deleted while running on cn=config */
1366                 if ( si->si_ctype < 1 ) {
1367                         if ( si->si_ctype == -1 ) {
1368                                 si->si_ctype = 0;
1369                                 freeinfo = 1;
1370                         }
1371                         if ( si->si_conn )
1372                                 dostop = 1;
1373                         rc = -1;
1374                 }
1375
1376                 if ( rc != SYNC_PAUSED ) {
1377                         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1378                                 /* If we succeeded, enable the connection for further listening.
1379                                  * If we failed, tear down the connection and reschedule.
1380                                  */
1381                                 if ( rc == LDAP_SUCCESS ) {
1382                                         if ( si->si_conn ) {
1383                                                 connection_client_enable( si->si_conn );
1384                                         } else {
1385                                                 si->si_conn = connection_client_setup( s, do_syncrepl, arg );
1386                                         } 
1387                                 } else if ( si->si_conn ) {
1388                                         dostop = 1;
1389                                 }
1390                         } else {
1391                                 if ( rc == -2 ) rc = 0;
1392                         }
1393                 }
1394         }
1395
1396         /* At this point, we have 5 cases:
1397          * 1) for any hard failure, give up and remove this task
1398          * 2) for ServerDown, reschedule this task to run later
1399          * 3) for threadpool pause, reschedule to run immediately
1400          * 4) for Refresh and Success, reschedule to run
1401          * 5) for Persist and Success, reschedule to defer
1402          */
1403         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1404
1405         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask ) ) {
1406                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1407         }
1408
1409         if ( dostop ) {
1410                 connection_client_stop( si->si_conn );
1411                 si->si_conn = NULL;
1412         }
1413
1414         if ( rc == SYNC_PAUSED ) {
1415                 rtask->interval.tv_sec = 0;
1416                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1417                 rtask->interval.tv_sec = si->si_interval;
1418                 rc = 0;
1419         } else if ( rc == LDAP_SUCCESS ) {
1420                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1421                         defer = 0;
1422                 }
1423                 rtask->interval.tv_sec = si->si_interval;
1424                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1425                 if ( si->si_retrynum ) {
1426                         for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1427                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1428                         }
1429                         si->si_retrynum[i] = RETRYNUM_TAIL;
1430                 }
1431         } else {
1432                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1433                         if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1434                                 break;
1435                 }
1436
1437                 if ( si->si_ctype < 1
1438                         || !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1439                         if ( si->si_re ) {
1440                                 ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1441                                 si->si_re = NULL;
1442                         }
1443                         fail = RETRYNUM_TAIL;
1444                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1445                         if ( si->si_retrynum[i] > 0 )
1446                                 si->si_retrynum[i]--;
1447                         fail = si->si_retrynum[i];
1448                         rtask->interval.tv_sec = si->si_retryinterval[i];
1449                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1450                         slap_wake_listener();
1451                 }
1452         }
1453
1454         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1455         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1456
1457         if ( rc ) {
1458                 if ( fail == RETRYNUM_TAIL ) {
1459                         Debug( LDAP_DEBUG_ANY,
1460                                 "do_syncrepl: %s rc %d quitting\n",
1461                                 si->si_ridtxt, rc, 0 );
1462                 } else if ( fail > 0 ) {
1463                         Debug( LDAP_DEBUG_ANY,
1464                                 "do_syncrepl: %s rc %d retrying (%d retries left)\n",
1465                                 si->si_ridtxt, rc, fail );
1466                 } else {
1467                         Debug( LDAP_DEBUG_ANY,
1468                                 "do_syncrepl: %s rc %d retrying\n",
1469                                 si->si_ridtxt, rc, 0 );
1470                 }
1471         }
1472
1473         /* Do final delete cleanup */
1474         if ( freeinfo ) {
1475                 syncinfo_free( si, 0 );
1476         }
1477         return NULL;
1478 }
1479
1480 static slap_verbmasks modops[] = {
1481         { BER_BVC("add"), LDAP_REQ_ADD },
1482         { BER_BVC("delete"), LDAP_REQ_DELETE },
1483         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1484         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1485         { BER_BVNULL, 0 }
1486 };
1487
1488 static Modifications *
1489 syncrepl_accesslog_mods(
1490         syncinfo_t *si,
1491         struct berval *vals
1492 )
1493 {
1494         char *colon;
1495         const char *text;
1496         AttributeDescription *ad;
1497         struct berval bv, bv2;
1498         short op;
1499         Modifications *mod = NULL, *modlist = NULL, **modtail;
1500         int i;
1501
1502         modtail = &modlist;
1503
1504         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1505                 ad = NULL;
1506                 bv = vals[i];
1507
1508                 colon = ber_bvchr( &bv, ':' );
1509                 if ( !colon ) {
1510                         /* Invalid */
1511                         continue;
1512                 }
1513
1514                 bv.bv_len = colon - bv.bv_val;
1515                 if ( slap_bv2ad( &bv, &ad, &text ) ) {
1516                         /* Invalid */
1517                         continue;
1518                 }
1519
1520                 /* Ignore dynamically generated attrs */
1521                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1522                         continue;
1523                 }
1524
1525                 /* Ignore excluded attrs */
1526                 if ( ldap_charray_inlist( si->si_exattrs,
1527                         ad->ad_type->sat_cname.bv_val ) )
1528                 {
1529                         continue;
1530                 }
1531
1532                 switch(colon[1]) {
1533                 case '+':       op = LDAP_MOD_ADD; break;
1534                 case '-':       op = LDAP_MOD_DELETE; break;
1535                 case '=':       op = LDAP_MOD_REPLACE; break;
1536                 case '#':       op = LDAP_MOD_INCREMENT; break;
1537                 default:        continue;
1538                 }
1539
1540                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1541                         mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1542                         mod->sml_flags = 0;
1543                         mod->sml_op = op;
1544                         mod->sml_next = NULL;
1545                         mod->sml_desc = ad;
1546                         mod->sml_type = ad->ad_cname;
1547                         mod->sml_values = NULL;
1548                         mod->sml_nvalues = NULL;
1549                         mod->sml_numvals = 0;
1550
1551                         *modtail = mod;
1552                         modtail = &mod->sml_next;
1553                 }
1554                 if ( colon[2] == ' ' ) {
1555                         bv.bv_val = colon + 3;
1556                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1557                         ber_dupbv( &bv2, &bv );
1558                         ber_bvarray_add( &mod->sml_values, &bv2 );
1559                         mod->sml_numvals++;
1560                 }
1561         }
1562         return modlist;
1563 }
1564
1565 static Modifications *
1566 syncrepl_changelog_mods(
1567         syncinfo_t *si,
1568         struct berval *vals
1569 )
1570 {
1571         return NULL;    /* FIXME */
1572 }
1573
1574 static int
1575 syncrepl_message_to_op(
1576         syncinfo_t      *si,
1577         Operation       *op,
1578         LDAPMessage     *msg
1579 )
1580 {
1581         BerElement      *ber = NULL;
1582         Modifications   *modlist = NULL;
1583         logschema *ls;
1584         SlapReply rs = { REP_RESULT };
1585         slap_callback cb = { NULL, null_callback, NULL, NULL };
1586
1587         const char      *text;
1588         char txtbuf[SLAP_TEXT_BUFLEN];
1589         size_t textlen = sizeof txtbuf;
1590
1591         struct berval   bdn, dn = BER_BVNULL, ndn;
1592         struct berval   bv, *bvals = NULL;
1593         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1594                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1595                 psup = BER_BVNULL, nsup = BER_BVNULL;
1596         int             rc, deleteOldRdn = 0, freeReqDn = 0;
1597         int             do_graduate = 0;
1598
1599         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1600                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1601                         "Message type should be entry (%d)",
1602                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1603                 return -1;
1604         }
1605
1606         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1607                 ls = &accesslog_sc;
1608         else
1609                 ls = &changelog_sc;
1610
1611         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1612
1613         if ( rc != LDAP_SUCCESS ) {
1614                 Debug( LDAP_DEBUG_ANY,
1615                         "syncrepl_message_to_op: %s dn get failed (%d)",
1616                         si->si_ridtxt, rc, 0 );
1617                 return rc;
1618         }
1619
1620         op->o_tag = LBER_DEFAULT;
1621         op->o_bd = si->si_wbe;
1622
1623         if ( BER_BVISEMPTY( &bdn ) && !BER_BVISEMPTY( &op->o_bd->be_nsuffix[0] ) ) {
1624                 Debug( LDAP_DEBUG_ANY,
1625                         "syncrepl_message_to_op: %s got empty dn",
1626                         si->si_ridtxt, 0, 0 );
1627                 return LDAP_OTHER;
1628         }
1629
1630         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
1631                 == LDAP_SUCCESS ) {
1632                 if ( bv.bv_val == NULL )
1633                         break;
1634
1635                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
1636                         bdn = bvals[0];
1637                         rc = dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1638                         if ( rc != LDAP_SUCCESS ) {
1639                                 Debug( LDAP_DEBUG_ANY,
1640                                         "syncrepl_message_to_op: %s "
1641                                         "dn \"%s\" normalization failed (%d)",
1642                                         si->si_ridtxt, bdn.bv_val, rc );
1643                                 rc = -1;
1644                                 ch_free( bvals );
1645                                 goto done;
1646                         }
1647                         ber_dupbv( &op->o_req_dn, &dn );
1648                         ber_dupbv( &op->o_req_ndn, &ndn );
1649                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1650                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1651                         freeReqDn = 1;
1652                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
1653                         int i = verb_to_mask( bvals[0].bv_val, modops );
1654                         if ( i < 0 ) {
1655                                 Debug( LDAP_DEBUG_ANY,
1656                                         "syncrepl_message_to_op: %s unknown op %s",
1657                                         si->si_ridtxt, bvals[0].bv_val, 0 );
1658                                 ch_free( bvals );
1659                                 rc = -1;
1660                                 goto done;
1661                         }
1662                         op->o_tag = modops[i].mask;
1663                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
1664                         /* Parse attribute into modlist */
1665                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
1666                                 modlist = syncrepl_accesslog_mods( si, bvals );
1667                         } else {
1668                                 modlist = syncrepl_changelog_mods( si, bvals );
1669                         }
1670                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
1671                         rdn = bvals[0];
1672                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
1673                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
1674                                 deleteOldRdn = 1;
1675                         }
1676                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
1677                         sup = bvals[0];
1678                 } else if ( !ber_bvstrcasecmp( &bv,
1679                         &slap_schema.si_ad_entryCSN->ad_cname ) )
1680                 {
1681                         slap_queue_csn( op, bvals );
1682                         do_graduate = 1;
1683                 }
1684                 ch_free( bvals );
1685         }
1686
1687         /* If we didn't get a mod type or a target DN, bail out */
1688         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
1689                 rc = -1;
1690                 goto done;
1691         }
1692
1693         op->o_callback = &cb;
1694         slap_op_time( &op->o_time, &op->o_tincr );
1695
1696         switch( op->o_tag ) {
1697         case LDAP_REQ_ADD:
1698         case LDAP_REQ_MODIFY:
1699                 /* If we didn't get required data, bail */
1700                 if ( !modlist ) goto done;
1701
1702                 rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
1703
1704                 if ( rc != LDAP_SUCCESS ) {
1705                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1706                                 "mods check (%s)\n",
1707                                 si->si_ridtxt, text, 0 );
1708                         goto done;
1709                 }
1710
1711                 if ( op->o_tag == LDAP_REQ_ADD ) {
1712                         Entry *e = entry_alloc();
1713                         op->ora_e = e;
1714                         op->ora_e->e_name = op->o_req_dn;
1715                         op->ora_e->e_nname = op->o_req_ndn;
1716                         freeReqDn = 0;
1717                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1718                         if( rc != LDAP_SUCCESS ) {
1719                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1720                                 "mods2entry (%s)\n",
1721                                         si->si_ridtxt, text, 0 );
1722                         } else {
1723                                 rc = op->o_bd->be_add( op, &rs );
1724                                 Debug( LDAP_DEBUG_SYNC,
1725                                         "syncrepl_message_to_op: %s be_add %s (%d)\n", 
1726                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1727                                 do_graduate = 0;
1728                         }
1729                         if ( e == op->ora_e )
1730                                 be_entry_release_w( op, op->ora_e );
1731                 } else {
1732                         op->orm_modlist = modlist;
1733                         op->o_bd = si->si_wbe;
1734                         rc = op->o_bd->be_modify( op, &rs );
1735                         modlist = op->orm_modlist;
1736                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1737                                 "syncrepl_message_to_op: %s be_modify %s (%d)\n", 
1738                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
1739                         op->o_bd = si->si_be;
1740                         do_graduate = 0;
1741                 }
1742                 break;
1743         case LDAP_REQ_MODRDN:
1744                 if ( BER_BVISNULL( &rdn ) ) goto done;
1745
1746                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
1747                         goto done;
1748                 }
1749                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
1750                         goto done;
1751                 }
1752                 if ( !BER_BVISNULL( &sup ) ) {
1753                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ) ) {
1754                                 goto done;
1755                         }
1756                         op->orr_newSup = &psup;
1757                         op->orr_nnewSup = &nsup;
1758                 } else {
1759                         op->orr_newSup = NULL;
1760                         op->orr_nnewSup = NULL;
1761                 }
1762                 op->orr_newrdn = prdn;
1763                 op->orr_nnewrdn = nrdn;
1764                 op->orr_deleteoldrdn = deleteOldRdn;
1765                 op->orr_modlist = NULL;
1766                 if ( slap_modrdn2mods( op, &rs ) ) {
1767                         goto done;
1768                 }
1769
1770                 /* Append modlist for operational attrs */
1771                 {
1772                         Modifications *m;
1773
1774                         for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
1775                                 ;
1776                         m->sml_next = modlist;
1777                         modlist = NULL;
1778                 }
1779                 rc = op->o_bd->be_modrdn( op, &rs );
1780                 slap_mods_free( op->orr_modlist, 1 );
1781                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1782                         "syncrepl_message_to_op: %s be_modrdn %s (%d)\n", 
1783                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1784                 do_graduate = 0;
1785                 break;
1786         case LDAP_REQ_DELETE:
1787                 rc = op->o_bd->be_delete( op, &rs );
1788                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1789                         "syncrepl_message_to_op: %s be_delete %s (%d)\n", 
1790                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1791                 do_graduate = 0;
1792                 break;
1793         }
1794 done:
1795         if ( do_graduate )
1796                 slap_graduate_commit_csn( op );
1797         op->o_bd = si->si_be;
1798         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
1799         BER_BVZERO( &op->o_csn );
1800         if ( modlist ) {
1801                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1802         }
1803         if ( !BER_BVISNULL( &rdn ) ) {
1804                 if ( !BER_BVISNULL( &nsup ) ) {
1805                         ch_free( nsup.bv_val );
1806                 }
1807                 if ( !BER_BVISNULL( &psup ) ) {
1808                         ch_free( psup.bv_val );
1809                 }
1810                 if ( !BER_BVISNULL( &nrdn ) ) {
1811                         ch_free( nrdn.bv_val );
1812                 }
1813                 if ( !BER_BVISNULL( &prdn ) ) {
1814                         ch_free( prdn.bv_val );
1815                 }
1816         }
1817         if ( freeReqDn ) {
1818                 ch_free( op->o_req_ndn.bv_val );
1819                 ch_free( op->o_req_dn.bv_val );
1820         }
1821         ber_free( ber, 0 );
1822         return rc;
1823 }
1824
1825 static int
1826 syncrepl_message_to_entry(
1827         syncinfo_t      *si,
1828         Operation       *op,
1829         LDAPMessage     *msg,
1830         Modifications   **modlist,
1831         Entry                   **entry,
1832         int             syncstate
1833 )
1834 {
1835         Entry           *e = NULL;
1836         BerElement      *ber = NULL;
1837         Modifications   tmp;
1838         Modifications   *mod;
1839         Modifications   **modtail = modlist;
1840
1841         const char      *text;
1842         char txtbuf[SLAP_TEXT_BUFLEN];
1843         size_t textlen = sizeof txtbuf;
1844
1845         struct berval   bdn = BER_BVNULL, dn, ndn;
1846         int             rc, is_ctx;
1847
1848         *modlist = NULL;
1849
1850         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1851                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
1852                         "Message type should be entry (%d)",
1853                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1854                 return -1;
1855         }
1856
1857         op->o_tag = LDAP_REQ_ADD;
1858
1859         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1860         if ( rc != LDAP_SUCCESS ) {
1861                 Debug( LDAP_DEBUG_ANY,
1862                         "syncrepl_message_to_entry: %s dn get failed (%d)",
1863                         si->si_ridtxt, rc, 0 );
1864                 return rc;
1865         }
1866
1867         if ( BER_BVISEMPTY( &bdn ) && !BER_BVISEMPTY( &op->o_bd->be_nsuffix[0] ) ) {
1868                 Debug( LDAP_DEBUG_ANY,
1869                         "syncrepl_message_to_entry: %s got empty dn",
1870                         si->si_ridtxt, 0, 0 );
1871                 return LDAP_OTHER;
1872         }
1873
1874         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1875                 /* NOTE: this could be done even before decoding the DN,
1876                  * although encoding errors wouldn't be detected */
1877                 rc = LDAP_SUCCESS;
1878                 goto done;
1879         }
1880
1881         if ( entry == NULL ) {
1882                 return -1;
1883         }
1884
1885         rc = dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1886         if ( rc != LDAP_SUCCESS ) {
1887                 /* One of the things that could happen is that the schema
1888                  * is not lined-up; this could result in unknown attributes.
1889                  * A value non conformant to the syntax should be unlikely,
1890                  * except when replicating between different versions
1891                  * of the software, or when syntax validation bugs are fixed
1892                  */
1893                 Debug( LDAP_DEBUG_ANY,
1894                         "syncrepl_message_to_entry: "
1895                         "%s dn \"%s\" normalization failed (%d)",
1896                         si->si_ridtxt, bdn.bv_val, rc );
1897                 return rc;
1898         }
1899
1900         ber_dupbv( &op->o_req_dn, &dn );
1901         ber_dupbv( &op->o_req_ndn, &ndn );
1902         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1903         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1904
1905         is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
1906
1907         e = entry_alloc();
1908         e->e_name = op->o_req_dn;
1909         e->e_nname = op->o_req_ndn;
1910
1911         while ( ber_remaining( ber ) ) {
1912                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1913                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1914                 {
1915                         break;
1916                 }
1917
1918                 /* Drop all updates to the contextCSN of the context entry
1919                  * (ITS#4622, etc.)
1920                  */
1921                 if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
1922                         slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
1923                         ber_bvarray_free( tmp.sml_values );
1924                         continue;
1925                 }
1926
1927                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
1928
1929                 mod->sml_op = LDAP_MOD_REPLACE;
1930                 mod->sml_flags = 0;
1931                 mod->sml_next = NULL;
1932                 mod->sml_desc = NULL;
1933                 mod->sml_type = tmp.sml_type;
1934                 mod->sml_values = tmp.sml_values;
1935                 mod->sml_nvalues = NULL;
1936                 mod->sml_numvals = 0;   /* slap_mods_check will set this */
1937
1938                 *modtail = mod;
1939                 modtail = &mod->sml_next;
1940         }
1941
1942         if ( *modlist == NULL ) {
1943                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
1944                         si->si_ridtxt, 0, 0 );
1945                 rc = -1;
1946                 goto done;
1947         }
1948
1949         rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
1950
1951         if ( rc != LDAP_SUCCESS ) {
1952                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
1953                         si->si_ridtxt, text, 0 );
1954                 goto done;
1955         }
1956
1957         /* Strip out dynamically generated attrs */
1958         for ( modtail = modlist; *modtail ; ) {
1959                 mod = *modtail;
1960                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1961                         *modtail = mod->sml_next;
1962                         slap_mod_free( &mod->sml_mod, 0 );
1963                         ch_free( mod );
1964                 } else {
1965                         modtail = &mod->sml_next;
1966                 }
1967         }
1968
1969         /* Strip out attrs in exattrs list */
1970         for ( modtail = modlist; *modtail ; ) {
1971                 mod = *modtail;
1972                 if ( ldap_charray_inlist( si->si_exattrs,
1973                         mod->sml_desc->ad_type->sat_cname.bv_val ) )
1974                 {
1975                         *modtail = mod->sml_next;
1976                         slap_mod_free( &mod->sml_mod, 0 );
1977                         ch_free( mod );
1978                 } else {
1979                         modtail = &mod->sml_next;
1980                 }
1981         }
1982
1983         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1984         if( rc != LDAP_SUCCESS ) {
1985                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
1986                         si->si_ridtxt, text, 0 );
1987         }
1988
1989 done:
1990         ber_free( ber, 0 );
1991         if ( rc != LDAP_SUCCESS ) {
1992                 if ( e ) {
1993                         entry_free( e );
1994                         e = NULL;
1995                 }
1996         }
1997         if ( entry )
1998                 *entry = e;
1999
2000         return rc;
2001 }
2002
2003 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
2004
2005 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
2006  * entry if a previous refresh was interrupted before sending us a new
2007  * context state. We try to compare the new entry to the existing entry
2008  * and ignore the new entry if they are the same.
2009  *
2010  * Also, we may get an update where the entryDN has changed, due to
2011  * a ModDn on the provider. We detect this as well, so we can issue
2012  * the corresponding operation locally.
2013  *
2014  * In the case of a modify, we get a list of all the attributes
2015  * in the original entry. Rather than deleting the entry and re-adding it,
2016  * we issue a Modify request that deletes all the attributes and adds all
2017  * the new ones. This avoids the issue of trying to delete/add a non-leaf
2018  * entry.
2019  *
2020  * We otherwise distinguish ModDN from Modify; in the case of
2021  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
2022  * operational attributes from the entry, and do a regular ModDN.
2023  */
2024 typedef struct dninfo {
2025         Entry *new_entry;
2026         struct berval dn;
2027         struct berval ndn;
2028         struct berval nnewSup;
2029         int renamed;    /* Was an existing entry renamed? */
2030         int delOldRDN;  /* Was old RDN deleted? */
2031         Modifications **modlist;        /* the modlist we received */
2032         Modifications *mods;    /* the modlist we compared */
2033         Attribute *oldNattr;    /* old naming attr */
2034         AttributeDescription *oldDesc;  /* for renames */
2035         AttributeDescription *newDesc;  /* for renames */
2036 } dninfo;
2037
2038 /* return 1 if inserted, 0 otherwise */
2039 static int
2040 avl_presentlist_insert(
2041         syncinfo_t* si,
2042         struct berval *syncUUID )
2043 {
2044         struct berval *syncuuid_bv = ch_malloc( sizeof( struct berval ) + syncUUID->bv_len + 1 );
2045
2046         syncuuid_bv->bv_len = syncUUID->bv_len;
2047         syncuuid_bv->bv_val = (char *)&syncuuid_bv[1];
2048         AC_MEMCPY( syncuuid_bv->bv_val, syncUUID->bv_val, syncUUID->bv_len );
2049         syncuuid_bv->bv_val[ syncuuid_bv->bv_len ] = '\0';
2050
2051         if ( avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
2052                 syncuuid_cmp, avl_dup_error ) )
2053         {
2054                 ch_free( syncuuid_bv );
2055                 return 0;
2056         }
2057
2058         return 1;
2059 }
2060
2061 static int
2062 syncrepl_entry(
2063         syncinfo_t* si,
2064         Operation *op,
2065         Entry* entry,
2066         Modifications** modlist,
2067         int syncstate,
2068         struct berval* syncUUID,
2069         struct berval* syncCSN )
2070 {
2071         Backend *be = op->o_bd;
2072         slap_callback   cb = { NULL, NULL, NULL, NULL };
2073         int syncuuid_inserted = 0;
2074         struct berval   syncUUID_strrep = BER_BVNULL;
2075
2076         SlapReply       rs_search = {REP_RESULT};
2077         SlapReply       rs_delete = {REP_RESULT};
2078         SlapReply       rs_add = {REP_RESULT};
2079         SlapReply       rs_modify = {REP_RESULT};
2080         Filter f = {0};
2081         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2082         int rc = LDAP_SUCCESS;
2083
2084         struct berval pdn = BER_BVNULL;
2085         dninfo dni = {0};
2086         int     retry = 1;
2087         int     freecsn = 1;
2088
2089         Debug( LDAP_DEBUG_SYNC,
2090                 "syncrepl_entry: %s LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_%s)\n",
2091                 si->si_ridtxt, syncrepl_state2str( syncstate ), 0 );
2092
2093         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
2094                 if ( !si->si_refreshPresent && !si->si_refreshDone ) {
2095                         syncuuid_inserted = avl_presentlist_insert( si, syncUUID );
2096                 }
2097         }
2098
2099         if ( syncstate == LDAP_SYNC_PRESENT ) {
2100                 return 0;
2101         } else if ( syncstate != LDAP_SYNC_DELETE ) {
2102                 if ( entry == NULL ) {
2103                         return 0;
2104                 }
2105         }
2106
2107         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
2108         if ( syncstate != LDAP_SYNC_DELETE ) {
2109                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
2110
2111                 if ( a == NULL ) {
2112                         /* add if missing */
2113                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
2114                                 &syncUUID_strrep, syncUUID );
2115
2116                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
2117                         /* replace only if necessary */
2118                         if ( a->a_nvals != a->a_vals ) {
2119                                 ber_memfree( a->a_nvals[0].bv_val );
2120                                 ber_dupbv( &a->a_nvals[0], syncUUID );
2121                         }
2122                         ber_memfree( a->a_vals[0].bv_val );
2123                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
2124                 }
2125         }
2126
2127         f.f_choice = LDAP_FILTER_EQUALITY;
2128         f.f_ava = &ava;
2129         ava.aa_desc = slap_schema.si_ad_entryUUID;
2130         ava.aa_value = *syncUUID;
2131
2132         if ( syncuuid_inserted ) {
2133                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
2134                         si->si_ridtxt, syncUUID_strrep.bv_val, 0 );
2135         }
2136         op->ors_filter = &f;
2137
2138         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
2139         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
2140                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
2141         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
2142         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
2143                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
2144         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
2145         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
2146
2147         op->o_tag = LDAP_REQ_SEARCH;
2148         op->ors_scope = LDAP_SCOPE_SUBTREE;
2149         op->ors_deref = LDAP_DEREF_NEVER;
2150
2151         /* get the entry for this UUID */
2152         op->o_req_dn = si->si_base;
2153         op->o_req_ndn = si->si_base;
2154
2155         op->o_time = slap_get_time();
2156         op->ors_tlimit = SLAP_NO_LIMIT;
2157         op->ors_slimit = 1;
2158         op->ors_limit = NULL;
2159
2160         op->ors_attrs = slap_anlist_all_attributes;
2161         op->ors_attrsonly = 0;
2162
2163         /* set callback function */
2164         op->o_callback = &cb;
2165         cb.sc_response = dn_callback;
2166         cb.sc_private = &dni;
2167         dni.new_entry = entry;
2168         dni.modlist = modlist;
2169
2170         rc = be->be_search( op, &rs_search );
2171         Debug( LDAP_DEBUG_SYNC,
2172                         "syncrepl_entry: %s be_search (%d)\n", 
2173                         si->si_ridtxt, rc, 0 );
2174
2175         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
2176                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2177         }
2178
2179         cb.sc_response = null_callback;
2180         cb.sc_private = si;
2181
2182         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
2183                 Debug( LDAP_DEBUG_SYNC,
2184                                 "syncrepl_entry: %s %s\n",
2185                                 si->si_ridtxt, entry->e_name.bv_val, 0 );
2186         } else {
2187                 Debug( LDAP_DEBUG_SYNC,
2188                                 "syncrepl_entry: %s %s\n",
2189                                 si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
2190         }
2191
2192         assert( BER_BVISNULL( &op->o_csn ) );
2193         if ( syncCSN ) {
2194                 slap_queue_csn( op, syncCSN );
2195         }
2196
2197         slap_op_time( &op->o_time, &op->o_tincr );
2198         switch ( syncstate ) {
2199         case LDAP_SYNC_ADD:
2200         case LDAP_SYNC_MODIFY:
2201                 if ( BER_BVISNULL( &op->o_csn ))
2202                 {
2203
2204                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
2205                         if ( a ) {
2206                                 /* FIXME: op->o_csn is assumed to be
2207                                  * on the thread's slab; this needs
2208                                  * to be cleared ASAP.
2209                                  * What happens if already present?
2210                                  */
2211                                 assert( BER_BVISNULL( &op->o_csn ) );
2212                                 op->o_csn = a->a_vals[0];
2213                                 freecsn = 0;
2214                         }
2215                 }
2216 retry_add:;
2217                 if ( BER_BVISNULL( &dni.dn ) ) {
2218
2219                         op->o_req_dn = entry->e_name;
2220                         op->o_req_ndn = entry->e_nname;
2221                         op->o_tag = LDAP_REQ_ADD;
2222                         op->ora_e = entry;
2223                         op->o_bd = si->si_wbe;
2224
2225                         rc = op->o_bd->be_add( op, &rs_add );
2226                         Debug( LDAP_DEBUG_SYNC,
2227                                         "syncrepl_entry: %s be_add %s (%d)\n", 
2228                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2229                         switch ( rs_add.sr_err ) {
2230                         case LDAP_SUCCESS:
2231                                 if ( op->ora_e == entry ) {
2232                                         be_entry_release_w( op, entry );
2233                                 }
2234                                 entry = NULL;
2235                                 break;
2236
2237                         case LDAP_REFERRAL:
2238                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
2239                          * only if the suffix entry is not present */
2240                         case LDAP_NO_SUCH_OBJECT:
2241                                 rc = syncrepl_add_glue( op, entry );
2242                                 entry = NULL;
2243                                 break;
2244
2245                         /* if an entry was added via syncrepl_add_glue(),
2246                          * it likely has no entryUUID, so the previous
2247                          * be_search() doesn't find it.  In this case,
2248                          * give syncrepl a chance to modify it. Also
2249                          * allow for entries that were recreated with the
2250                          * same DN but a different entryUUID.
2251                          */
2252                         case LDAP_ALREADY_EXISTS:
2253                                 if ( retry ) {
2254                                         Operation       op2 = *op;
2255                                         SlapReply       rs2 = { 0 };
2256                                         slap_callback   cb2 = { 0 };
2257
2258                                         op2.o_bd = be;
2259                                         op2.o_tag = LDAP_REQ_SEARCH;
2260                                         op2.o_req_dn = entry->e_name;
2261                                         op2.o_req_ndn = entry->e_nname;
2262                                         op2.ors_scope = LDAP_SCOPE_BASE;
2263                                         op2.ors_deref = LDAP_DEREF_NEVER;
2264                                         op2.ors_attrs = slap_anlist_all_attributes;
2265                                         op2.ors_attrsonly = 0;
2266                                         op2.ors_limit = NULL;
2267                                         op2.ors_slimit = 1;
2268                                         op2.ors_tlimit = SLAP_NO_LIMIT;
2269
2270                                         f.f_choice = LDAP_FILTER_PRESENT;
2271                                         f.f_desc = slap_schema.si_ad_objectClass;
2272                                         op2.ors_filter = &f;
2273                                         op2.ors_filterstr = generic_filterstr;
2274
2275                                         op2.o_callback = &cb2;
2276                                         cb2.sc_response = dn_callback;
2277                                         cb2.sc_private = &dni;
2278
2279                                         rc = be->be_search( &op2, &rs2 );
2280                                         if ( rc ) goto done;
2281
2282                                         retry = 0;
2283                                         slap_op_time( &op->o_time, &op->o_tincr );
2284                                         goto retry_add;
2285                                 }
2286                                 /* FALLTHRU */
2287
2288                         default:
2289                                 Debug( LDAP_DEBUG_ANY,
2290                                         "syncrepl_entry: %s be_add %s failed (%d)\n",
2291                                         si->si_ridtxt, op->o_req_dn.bv_val, rs_add.sr_err );
2292                                 break;
2293                         }
2294                         syncCSN = NULL;
2295                         op->o_bd = be;
2296                         goto done;
2297                 }
2298                 /* FALLTHRU */
2299                 op->o_req_dn = dni.dn;
2300                 op->o_req_ndn = dni.ndn;
2301                 if ( dni.renamed ) {
2302                         struct berval noldp, newp;
2303                         Modifications *mod, **modtail, **ml, *m2;
2304                         int i, got_replace = 0, just_rename = 0;
2305
2306                         op->o_tag = LDAP_REQ_MODRDN;
2307                         dnRdn( &entry->e_name, &op->orr_newrdn );
2308                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
2309
2310                         if ( !BER_BVISNULL( &dni.nnewSup )) {
2311                                 dnParent( &entry->e_name, &newp );
2312                                 op->orr_newSup = &newp;
2313                                 op->orr_nnewSup = &dni.nnewSup;
2314                         } else {
2315                                 op->orr_newSup = NULL;
2316                                 op->orr_nnewSup = NULL;
2317                         }
2318                         op->orr_deleteoldrdn = dni.delOldRDN;
2319                         op->orr_modlist = NULL;
2320                         if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
2321                                 goto done;
2322                         }
2323
2324                         /* Drop the RDN-related mods from this op, because their
2325                          * equivalents were just setup by slap_modrdn2mods.
2326                          *
2327                          * If delOldRDN is TRUE then we should see a delete modop
2328                          * for oldDesc. We might see a replace instead.
2329                          *  delete with no values: therefore newDesc != oldDesc.
2330                          *   if oldNattr had only one value, then Drop this op.
2331                          *  delete with 1 value: can only be the oldRDN value. Drop op.
2332                          *  delete with N values: Drop oldRDN value, keep remainder.
2333                          *  replace with 1 value: if oldNattr had only one value and
2334                          *     newDesc == oldDesc, Drop this op.
2335                          * Any other cases must be left intact.
2336                          *
2337                          * We should also see an add modop for newDesc. (But not if
2338                          * we got a replace modop due to delOldRDN.) If it has
2339                          * multiple values, we'll have to drop the new RDN value.
2340                          */
2341                         modtail = &op->orr_modlist;
2342                         if ( dni.delOldRDN ) {
2343                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2344                                         if ( (*ml)->sml_desc == dni.oldDesc ) {
2345                                                 mod = *ml;
2346                                                 if ( mod->sml_op == LDAP_MOD_REPLACE &&
2347                                                         dni.oldDesc != dni.newDesc ) {
2348                                                         /* This Replace is due to other Mods.
2349                                                          * Just let it ride.
2350                                                          */
2351                                                         continue;
2352                                                 }
2353                                                 if ( mod->sml_numvals <= 1 &&
2354                                                         dni.oldNattr->a_numvals == 1 &&
2355                                                         ( mod->sml_op == LDAP_MOD_DELETE ||
2356                                                           mod->sml_op == LDAP_MOD_REPLACE )) {
2357                                                         if ( mod->sml_op == LDAP_MOD_REPLACE )
2358                                                                 got_replace = 1;
2359                                                         /* Drop this op */
2360                                                         *ml = mod->sml_next;
2361                                                         mod->sml_next = NULL;
2362                                                         slap_mods_free( mod, 1 );
2363                                                         break;
2364                                                 }
2365                                                 if ( mod->sml_op != LDAP_MOD_DELETE || mod->sml_numvals == 0 )
2366                                                         continue;
2367                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2368                                                         if ( m2->sml_desc == dni.oldDesc &&
2369                                                                 m2->sml_op == LDAP_MOD_DELETE ) break;
2370                                                 }
2371                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
2372                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2373                                                                 mod->sml_numvals--;
2374                                                                 ch_free( mod->sml_values[i].bv_val );
2375                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2376                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2377                                                                 if ( mod->sml_nvalues ) {
2378                                                                         ch_free( mod->sml_nvalues[i].bv_val );
2379                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2380                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2381                                                                 }
2382                                                                 break;
2383                                                         }
2384                                                 }
2385                                                 if ( !mod->sml_numvals ) {
2386                                                         /* Drop this op */
2387                                                         *ml = mod->sml_next;
2388                                                         mod->sml_next = NULL;
2389                                                         slap_mods_free( mod, 1 );
2390                                                 }
2391                                                 break;
2392                                         }
2393                                 }
2394                         }
2395                         if ( !got_replace ) {
2396                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2397                                         if ( (*ml)->sml_desc == dni.newDesc ) {
2398                                                 mod = *ml;
2399                                                 if ( mod->sml_op != LDAP_MOD_ADD )
2400                                                         continue;
2401                                                 if ( mod->sml_numvals == 1 ) {
2402                                                         /* Drop this op */
2403                                                         *ml = mod->sml_next;
2404                                                         mod->sml_next = NULL;
2405                                                         slap_mods_free( mod, 1 );
2406                                                         break;
2407                                                 }
2408                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2409                                                         if ( m2->sml_desc == dni.oldDesc &&
2410                                                                 m2->sml_op == SLAP_MOD_SOFTADD ) break;
2411                                                 }
2412                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
2413                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2414                                                                 mod->sml_numvals--;
2415                                                                 ch_free( mod->sml_values[i].bv_val );
2416                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2417                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2418                                                                 if ( mod->sml_nvalues ) {
2419                                                                         ch_free( mod->sml_nvalues[i].bv_val );
2420                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2421                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2422                                                                 }
2423                                                                 break;
2424                                                         }
2425                                                 }
2426                                                 break;
2427                                         }
2428                                 }
2429                         }
2430
2431                         /* RDNs must be NUL-terminated for back-ldap */
2432                         noldp = op->orr_newrdn;
2433                         ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
2434                         noldp = op->orr_nnewrdn;
2435                         ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
2436
2437                         /* Setup opattrs too */
2438                         {
2439                                 static AttributeDescription *nullattr = NULL;
2440                                 static AttributeDescription **const opattrs[] = {
2441                                         &slap_schema.si_ad_entryCSN,
2442                                         &slap_schema.si_ad_modifiersName,
2443                                         &slap_schema.si_ad_modifyTimestamp,
2444                                         &nullattr
2445                                 };
2446                                 AttributeDescription *opattr;
2447                                 int i;
2448
2449                                 modtail = &m2;
2450                                 /* pull mod off incoming modlist */
2451                                 for ( i = 0; (opattr = *opattrs[i]) != NULL; i++ ) {
2452                                         for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next )
2453                                         {
2454                                                 if ( (*ml)->sml_desc == opattr ) {
2455                                                         mod = *ml;
2456                                                         *ml = mod->sml_next;
2457                                                         mod->sml_next = NULL;
2458                                                         *modtail = mod;
2459                                                         modtail = &mod->sml_next;
2460                                                         break;
2461                                                 }
2462                                         }
2463                                 }
2464                                 /* If there are still Modifications left, put the opattrs
2465                                  * back, and let be_modify run. Otherwise, append the opattrs
2466                                  * to the orr_modlist.
2467                                  */
2468                                 if ( dni.mods ) {
2469                                         mod = dni.mods;
2470                                         /* don't set a CSN for the rename op */
2471                                         if ( syncCSN )
2472                                                 slap_graduate_commit_csn( op );
2473                                 } else {
2474                                         mod = op->orr_modlist;
2475                                         just_rename = 1;
2476                                 }
2477                                 for ( ; mod->sml_next; mod=mod->sml_next );
2478                                 mod->sml_next = m2;
2479                         }
2480                         op->o_bd = si->si_wbe;
2481                         rc = op->o_bd->be_modrdn( op, &rs_modify );
2482                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
2483                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
2484
2485                         slap_mods_free( op->orr_modlist, 1 );
2486                         Debug( LDAP_DEBUG_SYNC,
2487                                         "syncrepl_entry: %s be_modrdn %s (%d)\n", 
2488                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2489                         op->o_bd = be;
2490                         /* Renamed entries may still have other mods so just fallthru */
2491                         op->o_req_dn = entry->e_name;
2492                         op->o_req_ndn = entry->e_nname;
2493                         /* Use CSN on the modify */
2494                         if ( just_rename )
2495                                 syncCSN = NULL;
2496                         else if ( syncCSN )
2497                                 slap_queue_csn( op, syncCSN );
2498                 }
2499                 if ( dni.mods ) {
2500                         op->o_tag = LDAP_REQ_MODIFY;
2501                         op->orm_modlist = dni.mods;
2502                         op->orm_no_opattrs = 1;
2503                         op->o_bd = si->si_wbe;
2504
2505                         rc = op->o_bd->be_modify( op, &rs_modify );
2506                         slap_mods_free( op->orm_modlist, 1 );
2507                         op->orm_no_opattrs = 0;
2508                         Debug( LDAP_DEBUG_SYNC,
2509                                         "syncrepl_entry: %s be_modify %s (%d)\n", 
2510                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2511                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2512                                 Debug( LDAP_DEBUG_ANY,
2513                                         "syncrepl_entry: %s be_modify failed (%d)\n",
2514                                         si->si_ridtxt, rs_modify.sr_err, 0 );
2515                         }
2516                         syncCSN = NULL;
2517                         op->o_bd = be;
2518                 } else if ( !dni.renamed ) {
2519                         Debug( LDAP_DEBUG_SYNC,
2520                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
2521                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
2522                         if ( syncCSN ) {
2523                                 slap_graduate_commit_csn( op );
2524                                 syncCSN = NULL;
2525                         }
2526                 }
2527                 goto done;
2528         case LDAP_SYNC_DELETE :
2529                 if ( !BER_BVISNULL( &dni.dn ) ) {
2530                         op->o_req_dn = dni.dn;
2531                         op->o_req_ndn = dni.ndn;
2532                         op->o_tag = LDAP_REQ_DELETE;
2533                         op->o_bd = si->si_wbe;
2534                         rc = op->o_bd->be_delete( op, &rs_delete );
2535                         Debug( LDAP_DEBUG_SYNC,
2536                                         "syncrepl_entry: %s be_delete %s (%d)\n", 
2537                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2538
2539                         while ( rs_delete.sr_err == LDAP_SUCCESS
2540                                 && op->o_delete_glue_parent ) {
2541                                 op->o_delete_glue_parent = 0;
2542                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2543                                         slap_callback cb = { NULL };
2544                                         cb.sc_response = slap_null_cb;
2545                                         dnParent( &op->o_req_ndn, &pdn );
2546                                         op->o_req_dn = pdn;
2547                                         op->o_req_ndn = pdn;
2548                                         op->o_callback = &cb;
2549                                         op->o_bd->be_delete( op, &rs_delete );
2550                                 } else {
2551                                         break;
2552                                 }
2553                         }
2554                         syncCSN = NULL;
2555                         op->o_bd = be;
2556                 }
2557                 goto done;
2558
2559         default :
2560                 Debug( LDAP_DEBUG_ANY,
2561                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
2562                 goto done;
2563         }
2564
2565 done:
2566         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2567                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2568                 BER_BVZERO( &syncUUID_strrep );
2569         }
2570         if ( !BER_BVISNULL( &dni.ndn ) ) {
2571                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2572         }
2573         if ( !BER_BVISNULL( &dni.dn ) ) {
2574                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2575         }
2576         if ( entry ) {
2577                 entry_free( entry );
2578         }
2579         if ( syncCSN ) {
2580                 slap_graduate_commit_csn( op );
2581         }
2582         if ( !BER_BVISNULL( &op->o_csn ) && freecsn ) {
2583                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2584         }
2585         BER_BVZERO( &op->o_csn );
2586         return rc;
2587 }
2588
2589 static struct berval gcbva[] = {
2590         BER_BVC("top"),
2591         BER_BVC("glue"),
2592         BER_BVNULL
2593 };
2594
2595 #define NP_DELETE_ONE   2
2596
2597 static void
2598 syncrepl_del_nonpresent(
2599         Operation *op,
2600         syncinfo_t *si,
2601         BerVarray uuids,
2602         struct sync_cookie *sc,
2603         int m )
2604 {
2605         Backend* be = op->o_bd;
2606         slap_callback   cb = { NULL };
2607         SlapReply       rs_search = {REP_RESULT};
2608         SlapReply       rs_delete = {REP_RESULT};
2609         SlapReply       rs_modify = {REP_RESULT};
2610         struct nonpresent_entry *np_list, *np_prev;
2611         int rc;
2612         AttributeName   an[2];
2613
2614         struct berval pdn = BER_BVNULL;
2615         struct berval csn;
2616
2617         op->o_req_dn = si->si_base;
2618         op->o_req_ndn = si->si_base;
2619
2620         cb.sc_response = nonpresent_callback;
2621         cb.sc_private = si;
2622
2623         op->o_callback = &cb;
2624         op->o_tag = LDAP_REQ_SEARCH;
2625         op->ors_scope = si->si_scope;
2626         op->ors_deref = LDAP_DEREF_NEVER;
2627         op->o_time = slap_get_time();
2628         op->ors_tlimit = SLAP_NO_LIMIT;
2629
2630
2631         if ( uuids ) {
2632                 Filter uf;
2633                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
2634                 int i;
2635
2636                 op->ors_attrsonly = 1;
2637                 op->ors_attrs = slap_anlist_no_attrs;
2638                 op->ors_limit = NULL;
2639                 op->ors_filter = &uf;
2640
2641                 uf.f_ava = &eq;
2642                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2643                 uf.f_next = NULL;
2644                 uf.f_choice = LDAP_FILTER_EQUALITY;
2645                 si->si_refreshDelete |= NP_DELETE_ONE;
2646
2647                 for (i=0; uuids[i].bv_val; i++) {
2648                         op->ors_slimit = 1;
2649                         uf.f_av_value = uuids[i];
2650                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2651                         rc = be->be_search( op, &rs_search );
2652                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2653                 }
2654                 si->si_refreshDelete ^= NP_DELETE_ONE;
2655         } else {
2656                 Filter *cf, *of;
2657                 Filter mmf[2];
2658                 AttributeAssertion mmaa;
2659
2660                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2661                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2662                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2663                 op->ors_attrs = an;
2664                 op->ors_slimit = SLAP_NO_LIMIT;
2665                 op->ors_tlimit = SLAP_NO_LIMIT;
2666                 op->ors_limit = NULL;
2667                 op->ors_attrsonly = 0;
2668                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2669                 /* In multimaster, updates can continue to arrive while
2670                  * we're searching. Limit the search result to entries
2671                  * older than our newest cookie CSN.
2672                  */
2673                 if ( SLAP_MULTIMASTER( op->o_bd )) {
2674                         Filter *f;
2675                         int i;
2676
2677                         f = mmf;
2678                         f->f_choice = LDAP_FILTER_AND;
2679                         f->f_next = op->ors_filter;
2680                         f->f_and = f+1;
2681                         of = f->f_and;
2682                         f = of;
2683                         f->f_choice = LDAP_FILTER_LE;
2684                         f->f_ava = &mmaa;
2685                         f->f_av_desc = slap_schema.si_ad_entryCSN;
2686                         f->f_next = NULL;
2687                         BER_BVZERO( &f->f_av_value );
2688                         for ( i=0; i<sc->numcsns; i++ ) {
2689                                 if ( ber_bvcmp( &sc->ctxcsn[i], &f->f_av_value ) > 0 )
2690                                         f->f_av_value = sc->ctxcsn[i];
2691                         }
2692                         of = op->ors_filter;
2693                         op->ors_filter = mmf;
2694                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2695                 } else {
2696                         cf = NULL;
2697                         op->ors_filterstr = si->si_filterstr;
2698                 }
2699                 op->o_nocaching = 1;
2700
2701
2702                 rc = be->be_search( op, &rs_search );
2703                 if ( SLAP_MULTIMASTER( op->o_bd )) {
2704                         op->ors_filter = of;
2705                 }
2706                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter, 1 );
2707                 if ( op->ors_filterstr.bv_val != si->si_filterstr.bv_val ) {
2708                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2709                 }
2710
2711         }
2712
2713         op->o_nocaching = 0;
2714
2715         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2716
2717                 if ( sc->ctxcsn && !BER_BVISNULL( &sc->ctxcsn[m] ) ) {
2718                         csn = sc->ctxcsn[m];
2719                 } else {
2720                         csn = si->si_syncCookie.ctxcsn[0];
2721                 }
2722
2723                 op->o_bd = si->si_wbe;
2724                 slap_queue_csn( op, &csn );
2725
2726                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2727                 while ( np_list != NULL ) {
2728                         LDAP_LIST_REMOVE( np_list, npe_link );
2729                         np_prev = np_list;
2730                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2731                         op->o_tag = LDAP_REQ_DELETE;
2732                         op->o_callback = &cb;
2733                         cb.sc_response = null_callback;
2734                         cb.sc_private = si;
2735                         op->o_req_dn = *np_prev->npe_name;
2736                         op->o_req_ndn = *np_prev->npe_nname;
2737                         rc = op->o_bd->be_delete( op, &rs_delete );
2738                         Debug( LDAP_DEBUG_SYNC,
2739                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
2740                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2741
2742                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2743                                 Modifications mod1, mod2;
2744                                 mod1.sml_op = LDAP_MOD_REPLACE;
2745                                 mod1.sml_flags = 0;
2746                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2747                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2748                                 mod1.sml_numvals = 2;
2749                                 mod1.sml_values = &gcbva[0];
2750                                 mod1.sml_nvalues = NULL;
2751                                 mod1.sml_next = &mod2;
2752
2753                                 mod2.sml_op = LDAP_MOD_REPLACE;
2754                                 mod2.sml_flags = 0;
2755                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2756                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2757                                 mod2.sml_numvals = 1;
2758                                 mod2.sml_values = &gcbva[1];
2759                                 mod2.sml_nvalues = NULL;
2760                                 mod2.sml_next = NULL;
2761
2762                                 op->o_tag = LDAP_REQ_MODIFY;
2763                                 op->orm_modlist = &mod1;
2764
2765                                 rc = op->o_bd->be_modify( op, &rs_modify );
2766                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2767                         }
2768
2769                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2770                                         op->o_delete_glue_parent ) {
2771                                 op->o_delete_glue_parent = 0;
2772                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2773                                         slap_callback cb = { NULL };
2774                                         cb.sc_response = slap_null_cb;
2775                                         dnParent( &op->o_req_ndn, &pdn );
2776                                         op->o_req_dn = pdn;
2777                                         op->o_req_ndn = pdn;
2778                                         op->o_callback = &cb;
2779                                         /* give it a root privil ? */
2780                                         op->o_bd->be_delete( op, &rs_delete );
2781                                 } else {
2782                                         break;
2783                                 }
2784                         }
2785
2786                         op->o_delete_glue_parent = 0;
2787
2788                         ber_bvfree( np_prev->npe_name );
2789                         ber_bvfree( np_prev->npe_nname );
2790                         ch_free( np_prev );
2791
2792                         if ( slapd_shutdown ) {
2793                                 break;
2794                         }
2795                 }
2796
2797                 slap_graduate_commit_csn( op );
2798                 op->o_bd = be;
2799
2800                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2801                 BER_BVZERO( &op->o_csn );
2802         }
2803
2804         return;
2805 }
2806
2807 int
2808 syncrepl_add_glue(
2809         Operation* op,
2810         Entry *e )
2811 {
2812         Backend *be = op->o_bd;
2813         slap_callback cb = { NULL };
2814         Attribute       *a;
2815         int     rc;
2816         int suffrdns;
2817         int i;
2818         struct berval dn = BER_BVNULL;
2819         struct berval ndn = BER_BVNULL;
2820         Entry   *glue;
2821         SlapReply       rs_add = {REP_RESULT};
2822         struct berval   ptr, nptr;
2823         char            *comma;
2824
2825         op->o_tag = LDAP_REQ_ADD;
2826         op->o_callback = &cb;
2827         cb.sc_response = null_callback;
2828         cb.sc_private = NULL;
2829
2830         dn = e->e_name;
2831         ndn = e->e_nname;
2832
2833         /* count RDNs in suffix */
2834         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2835                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2836                         comma++;
2837                         ptr.bv_len -= comma - ptr.bv_val;
2838                         ptr.bv_val = comma;
2839                         i++;
2840                 }
2841                 suffrdns = i;
2842         } else {
2843                 /* suffix is "" */
2844                 suffrdns = 0;
2845         }
2846
2847         /* Start with BE suffix */
2848         ptr = dn;
2849         for ( i = 0; i < suffrdns; i++ ) {
2850                 comma = ber_bvrchr( &ptr, ',' );
2851                 if ( comma != NULL ) {
2852                         ptr.bv_len = comma - ptr.bv_val;
2853                 } else {
2854                         ptr.bv_len = 0;
2855                         break;
2856                 }
2857         }
2858         
2859         if ( !BER_BVISEMPTY( &ptr ) ) {
2860                 dn.bv_len -= ptr.bv_len + 1;
2861                 dn.bv_val += ptr.bv_len + 1;
2862         }
2863
2864         /* the normalizedDNs are always the same length, no counting
2865          * required.
2866          */
2867         nptr = ndn;
2868         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2869                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2870                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2871
2872                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2873
2874         } else {
2875                 nptr.bv_len = 0;
2876         }
2877
2878         while ( ndn.bv_val > e->e_nname.bv_val ) {
2879                 glue = entry_alloc();
2880                 ber_dupbv( &glue->e_name, &dn );
2881                 ber_dupbv( &glue->e_nname, &ndn );
2882
2883                 a = attr_alloc( slap_schema.si_ad_objectClass );
2884
2885                 a->a_numvals = 2;
2886                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
2887                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2888                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2889                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2890
2891                 a->a_nvals = a->a_vals;
2892
2893                 a->a_next = glue->e_attrs;
2894                 glue->e_attrs = a;
2895
2896                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
2897
2898                 a->a_numvals = 1;
2899                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
2900                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2901                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2902
2903                 a->a_nvals = a->a_vals;
2904
2905                 a->a_next = glue->e_attrs;
2906                 glue->e_attrs = a;
2907
2908                 op->o_req_dn = glue->e_name;
2909                 op->o_req_ndn = glue->e_nname;
2910                 op->ora_e = glue;
2911                 rc = be->be_add ( op, &rs_add );
2912                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2913                         if ( op->ora_e == glue )
2914                                 be_entry_release_w( op, glue );
2915                 } else {
2916                 /* incl. ALREADY EXIST */
2917                         entry_free( glue );
2918                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2919                                 entry_free( e );
2920                                 return rc;
2921                         }
2922                 }
2923
2924                 /* Move to next child */
2925                 comma = ber_bvrchr( &ptr, ',' );
2926                 if ( comma == NULL ) {
2927                         break;
2928                 }
2929                 ptr.bv_len = comma - ptr.bv_val;
2930                 
2931                 dn.bv_val = ++comma;
2932                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2933
2934                 comma = ber_bvrchr( &nptr, ',' );
2935                 assert( comma != NULL );
2936                 nptr.bv_len = comma - nptr.bv_val;
2937
2938                 ndn.bv_val = ++comma;
2939                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2940         }
2941
2942         op->o_req_dn = e->e_name;
2943         op->o_req_ndn = e->e_nname;
2944         op->ora_e = e;
2945         rc = be->be_add ( op, &rs_add );
2946         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2947                 if ( op->ora_e == e )
2948                         be_entry_release_w( op, e );
2949         } else {
2950                 entry_free( e );
2951         }
2952
2953         return rc;
2954 }
2955
2956 static int
2957 syncrepl_updateCookie(
2958         syncinfo_t *si,
2959         Operation *op,
2960         struct berval *pdn,
2961         struct sync_cookie *syncCookie )
2962 {
2963         Backend *be = op->o_bd;
2964         Modifications mod;
2965         struct berval first = BER_BVNULL;
2966 #ifdef CHECK_CSN
2967         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
2968 #endif
2969
2970         int rc, i, j;
2971         ber_len_t len;
2972
2973         slap_callback cb = { NULL };
2974         SlapReply       rs_modify = {REP_RESULT};
2975
2976         mod.sml_op = LDAP_MOD_REPLACE;
2977         mod.sml_desc = slap_schema.si_ad_contextCSN;
2978         mod.sml_type = mod.sml_desc->ad_cname;
2979         mod.sml_flags = SLAP_MOD_INTERNAL;
2980         mod.sml_nvalues = NULL;
2981         mod.sml_next = NULL;
2982
2983         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
2984
2985 #ifdef CHECK_CSN
2986         for ( i=0; i<syncCookie->numcsns; i++ ) {
2987                 assert( !syn->ssyn_validate( syn, syncCookie->ctxcsn+i ));
2988         }
2989         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
2990                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
2991         }
2992 #endif
2993
2994         /* clone the cookieState CSNs so we can Replace the whole thing */
2995         mod.sml_numvals = si->si_cookieState->cs_num;
2996         mod.sml_values = op->o_tmpalloc(( mod.sml_numvals+1 )*sizeof(struct berval), op->o_tmpmemctx );
2997         for ( i=0; i<mod.sml_numvals; i++ )
2998                 mod.sml_values[i] = si->si_cookieState->cs_vals[i];
2999         BER_BVZERO( &mod.sml_values[i] );
3000
3001         /* find any CSNs in the syncCookie that are newer than the cookieState */
3002         for ( i=0; i<syncCookie->numcsns; i++ ) {
3003                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
3004                         if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
3005                                 continue;
3006                         len = syncCookie->ctxcsn[i].bv_len;
3007                         if ( len > si->si_cookieState->cs_vals[j].bv_len )
3008                                 len = si->si_cookieState->cs_vals[j].bv_len;
3009                         if ( memcmp( syncCookie->ctxcsn[i].bv_val,
3010                                 si->si_cookieState->cs_vals[j].bv_val, len ) > 0 ) {
3011                                 mod.sml_values[j] = syncCookie->ctxcsn[i];
3012                                 if ( BER_BVISNULL( &first ) ) {
3013                                         first = syncCookie->ctxcsn[i];
3014
3015                                 } else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
3016                                 {
3017                                         first = syncCookie->ctxcsn[i];
3018                                 }
3019                         }
3020                         break;
3021                 }
3022                 /* there was no match for this SID, it's a new CSN */
3023                 if ( j == si->si_cookieState->cs_num ) {
3024                         mod.sml_values = op->o_tmprealloc( mod.sml_values,
3025                                 ( mod.sml_numvals+2 )*sizeof(struct berval), op->o_tmpmemctx );
3026                         mod.sml_values[mod.sml_numvals++] = syncCookie->ctxcsn[i];
3027                         BER_BVZERO( &mod.sml_values[mod.sml_numvals] );
3028                         if ( BER_BVISNULL( &first ) ) {
3029                                 first = syncCookie->ctxcsn[i];
3030                         } else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
3031                         {
3032                                 first = syncCookie->ctxcsn[i];
3033                         }
3034                 }
3035         }
3036         /* Should never happen, ITS#5065 */
3037         if ( BER_BVISNULL( &first )) {
3038                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3039                 op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3040                 return 0;
3041         }
3042         op->o_bd = si->si_wbe;
3043         slap_queue_csn( op, &first );
3044
3045         op->o_tag = LDAP_REQ_MODIFY;
3046
3047         cb.sc_response = null_callback;
3048         cb.sc_private = si;
3049
3050         op->o_callback = &cb;
3051         op->o_req_dn = op->o_bd->be_suffix[0];
3052         op->o_req_ndn = op->o_bd->be_nsuffix[0];
3053
3054         /* update contextCSN */
3055         op->o_dont_replicate = 1;
3056
3057         op->orm_modlist = &mod;
3058         op->orm_no_opattrs = 1;
3059         rc = op->o_bd->be_modify( op, &rs_modify );
3060         op->orm_no_opattrs = 0;
3061         op->o_dont_replicate = 0;
3062
3063         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
3064                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
3065                 slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
3066                 /* If we replaced any old values */
3067                 for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3068                         if ( mod.sml_values[i].bv_val != si->si_cookieState->cs_vals[i].bv_val )
3069                                         ber_bvreplace( &si->si_cookieState->cs_vals[i],
3070                                                 &mod.sml_values[i] );
3071                 }
3072                 /* Handle any added values */
3073                 if ( i < mod.sml_numvals ) {
3074                         si->si_cookieState->cs_num = mod.sml_numvals;
3075                         value_add( &si->si_cookieState->cs_vals, &mod.sml_values[i] );
3076                         free( si->si_cookieState->cs_sids );
3077                         si->si_cookieState->cs_sids = slap_parse_csn_sids(
3078                                 si->si_cookieState->cs_vals, si->si_cookieState->cs_num, NULL );
3079                 }
3080
3081                 si->si_cookieState->cs_age++;
3082                 si->si_cookieAge = si->si_cookieState->cs_age;
3083         } else {
3084                 Debug( LDAP_DEBUG_ANY,
3085                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
3086                         si->si_ridtxt, rs_modify.sr_err, 0 );
3087         }
3088         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3089
3090         op->o_bd = be;
3091         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3092         BER_BVZERO( &op->o_csn );
3093         if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
3094         op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3095
3096 #ifdef CHECK_CSN
3097         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3098                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3099         }
3100 #endif
3101
3102         return rc;
3103 }
3104
3105 /* Compare the attribute from the old entry to the one in the new
3106  * entry. The Modifications from the new entry will either be left
3107  * in place, or changed to an Add or Delete as needed.
3108  */
3109 static void
3110 attr_cmp( Operation *op, Attribute *old, Attribute *new,
3111         Modifications ***mret, Modifications ***mcur )
3112 {
3113         int i, j;
3114         Modifications *mod, **modtail;
3115
3116         modtail = *mret;
3117
3118         if ( old ) {
3119                 int n, o, nn, no;
3120                 struct berval **adds, **dels;
3121                 /* count old and new */
3122                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
3123                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
3124
3125                 /* there MUST be both old and new values */
3126                 assert( o != 0 );
3127                 assert( n != 0 );
3128                 j = 0;
3129
3130                 adds = op->o_tmpalloc( sizeof(struct berval *) * n, op->o_tmpmemctx );
3131                 dels = op->o_tmpalloc( sizeof(struct berval *) * o, op->o_tmpmemctx );
3132
3133                 for ( i=0; i<o; i++ ) dels[i] = &old->a_vals[i];
3134                 for ( i=0; i<n; i++ ) adds[i] = &new->a_vals[i];
3135
3136                 nn = n; no = o;
3137
3138                 for ( i=0; i<o; i++ ) {
3139                         for ( j=0; j<n; j++ ) {
3140                                 if ( !adds[j] )
3141                                         continue;
3142                                 if ( bvmatch( dels[i], adds[j] ) ) {
3143                                         no--;
3144                                         nn--;
3145                                         adds[j] = NULL;
3146                                         dels[i] = NULL;
3147                                         break;
3148                                 }
3149                         }
3150                 }
3151
3152                 /* Don't delete/add an objectClass, always use the replace op.
3153                  * Modify would fail if provider has replaced entry with a new,
3154                  * and the new explicitly includes a superior of a class that was
3155                  * only included implicitly in the old entry.  Ref ITS#5517.
3156                  *
3157                  * Also use replace op if attr has no equality matching rule.
3158                  * (ITS#5781)
3159                  */
3160                 if ( nn && no < o &&
3161                         ( old->a_desc == slap_schema.si_ad_objectClass ||
3162                          !old->a_desc->ad_type->sat_equality ))
3163                         no = o;
3164
3165                 i = j;
3166                 /* all old values were deleted, just use the replace op */
3167                 if ( no == o ) {
3168                         i = j-1;
3169                 } else if ( no ) {
3170                 /* delete some values */
3171                         mod = ch_malloc( sizeof( Modifications ) );
3172                         mod->sml_op = LDAP_MOD_DELETE;
3173                         mod->sml_flags = 0;
3174                         mod->sml_desc = old->a_desc;
3175                         mod->sml_type = mod->sml_desc->ad_cname;
3176                         mod->sml_numvals = no;
3177                         mod->sml_values = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3178                         if ( old->a_vals != old->a_nvals ) {
3179                                 mod->sml_nvalues = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3180                         } else {
3181                                 mod->sml_nvalues = NULL;
3182                         }
3183                         j = 0;
3184                         for ( i = 0; i < o; i++ ) {
3185                                 if ( !dels[i] ) continue;
3186                                 ber_dupbv( &mod->sml_values[j], &old->a_vals[i] );
3187                                 if ( mod->sml_nvalues ) {
3188                                         ber_dupbv( &mod->sml_nvalues[j], &old->a_nvals[i] );
3189                                 }
3190                                 j++;
3191                         }
3192                         BER_BVZERO( &mod->sml_values[j] );
3193                         if ( mod->sml_nvalues ) {
3194                                 BER_BVZERO( &mod->sml_nvalues[j] );
3195                         }
3196                         *modtail = mod;
3197                         modtail = &mod->sml_next;
3198                         i = j;
3199                 }
3200                 op->o_tmpfree( dels, op->o_tmpmemctx );
3201                 /* some values were added */
3202                 if ( nn && no < o ) {
3203                         mod = ch_malloc( sizeof( Modifications ) );
3204                         mod->sml_op = LDAP_MOD_ADD;
3205                         mod->sml_flags = 0;
3206                         mod->sml_desc = old->a_desc;
3207                         mod->sml_type = mod->sml_desc->ad_cname;
3208                         mod->sml_numvals = nn;
3209                         mod->sml_values = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3210                         if ( old->a_vals != old->a_nvals ) {
3211                                 mod->sml_nvalues = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3212                         } else {
3213                                 mod->sml_nvalues = NULL;
3214                         }
3215                         j = 0;
3216                         for ( i = 0; i < n; i++ ) {
3217                                 if ( !adds[i] ) continue;
3218                                 ber_dupbv( &mod->sml_values[j], &new->a_vals[i] );
3219                                 if ( mod->sml_nvalues ) {
3220                                         ber_dupbv( &mod->sml_nvalues[j], &new->a_nvals[i] );
3221                                 }
3222                                 j++;
3223                         }
3224                         BER_BVZERO( &mod->sml_values[j] );
3225                         if ( mod->sml_nvalues ) {
3226                                 BER_BVZERO( &mod->sml_nvalues[j] );
3227                         }
3228                         *modtail = mod;
3229                         modtail = &mod->sml_next;
3230                         i = j;
3231                 }
3232                 op->o_tmpfree( adds, op->o_tmpmemctx );
3233         } else {
3234                 /* new attr, just use the new mod */
3235                 i = 0;
3236                 j = 1;
3237         }
3238         /* advance to next element */
3239         mod = **mcur;
3240         if ( mod ) {
3241                 if ( i != j ) {
3242                         **mcur = mod->sml_next;
3243                         *modtail = mod;
3244                         modtail = &mod->sml_next;
3245                 } else {
3246                         *mcur = &mod->sml_next;
3247                 }
3248         }
3249         *mret = modtail;
3250 }
3251
3252 /* Generate a set of modifications to change the old entry into the
3253  * new one. On input ml is a list of modifications equivalent to
3254  * the new entry. It will be massaged and the result will be stored
3255  * in mods.
3256  */
3257 void syncrepl_diff_entry( Operation *op, Attribute *old, Attribute *new,
3258         Modifications **mods, Modifications **ml, int is_ctx)
3259 {
3260         Modifications **modtail = mods;
3261
3262         /* We assume that attributes are saved in the same order
3263          * in the remote and local databases. So if we walk through
3264          * the attributeDescriptions one by one they should match in
3265          * lock step. If not, look for an add or delete.
3266          */
3267         while ( old && new )
3268         {
3269                 /* If we've seen this before, use its mod now */
3270                 if ( new->a_flags & SLAP_ATTR_IXADD ) {
3271                         attr_cmp( op, NULL, new, &modtail, &ml );
3272                         new = new->a_next;
3273                         continue;
3274                 }
3275                 /* Skip contextCSN */
3276                 if ( is_ctx && old->a_desc ==
3277                         slap_schema.si_ad_contextCSN ) {
3278                         old = old->a_next;
3279                         continue;
3280                 }
3281
3282                 if ( old->a_desc != new->a_desc ) {
3283                         Modifications *mod;
3284                         Attribute *tmp;
3285
3286                         /* If it's just been re-added later,
3287                          * remember that we've seen it.
3288                          */
3289                         tmp = attr_find( new, old->a_desc );
3290                         if ( tmp ) {
3291                                 tmp->a_flags |= SLAP_ATTR_IXADD;
3292                         } else {
3293                                 /* If it's a new attribute, pull it in.
3294                                  */
3295                                 tmp = attr_find( old, new->a_desc );
3296                                 if ( !tmp ) {
3297                                         attr_cmp( op, NULL, new, &modtail, &ml );
3298                                         new = new->a_next;
3299                                         continue;
3300                                 }
3301                                 /* Delete old attr */
3302                                 mod = ch_malloc( sizeof( Modifications ) );
3303                                 mod->sml_op = LDAP_MOD_DELETE;
3304                                 mod->sml_flags = 0;
3305                                 mod->sml_desc = old->a_desc;
3306                                 mod->sml_type = mod->sml_desc->ad_cname;
3307                                 mod->sml_numvals = 0;
3308                                 mod->sml_values = NULL;
3309                                 mod->sml_nvalues = NULL;
3310                                 *modtail = mod;
3311                                 modtail = &mod->sml_next;
3312                         }
3313                         old = old->a_next;
3314                         continue;
3315                 }
3316                 /* kludge - always update modifiersName so that it
3317                  * stays co-located with the other mod opattrs. But only
3318                  * if we know there are other valid mods.
3319                  */
3320                 if ( *mods && ( old->a_desc == slap_schema.si_ad_modifiersName ||
3321                         old->a_desc == slap_schema.si_ad_modifyTimestamp ))
3322                         attr_cmp( op, NULL, new, &modtail, &ml );
3323                 else
3324                         attr_cmp( op, old, new, &modtail, &ml );
3325                 new = new->a_next;
3326                 old = old->a_next;
3327         }
3328         *modtail = *ml;
3329         *ml = NULL;
3330 }
3331
3332 static int
3333 dn_callback(
3334         Operation*      op,
3335         SlapReply*      rs )
3336 {
3337         dninfo *dni = op->o_callback->sc_private;
3338
3339         if ( rs->sr_type == REP_SEARCH ) {
3340                 if ( !BER_BVISNULL( &dni->dn ) ) {
3341                         Debug( LDAP_DEBUG_ANY,
3342                                 "dn_callback : consistency error - "
3343                                 "entryUUID is not unique\n", 0, 0, 0 );
3344                 } else {
3345                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
3346                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
3347                         /* If there is a new entry, see if it differs from the old.
3348                          * We compare the non-normalized values so that cosmetic changes
3349                          * in the provider are always propagated.
3350                          */
3351                         if ( dni->new_entry ) {
3352                                 Modifications **modtail, **ml;
3353                                 Attribute *old, *new;
3354                                 struct berval old_rdn, new_rdn;
3355                                 struct berval old_p, new_p;
3356                                 int is_ctx, new_sup = 0;
3357
3358                                 /* If old entry is not a glue entry, make sure new entry
3359                                  * is actually newer than old entry
3360                                  */
3361                                 if ( !is_entry_glue( rs->sr_entry )) {
3362                                         old = attr_find( rs->sr_entry->e_attrs,
3363                                                 slap_schema.si_ad_entryCSN );
3364                                         new = attr_find( dni->new_entry->e_attrs,
3365                                                 slap_schema.si_ad_entryCSN );
3366                                         if ( new && old ) {
3367                                                 int rc;
3368                                                 ber_len_t len = old->a_vals[0].bv_len;
3369                                                 if ( len > new->a_vals[0].bv_len )
3370                                                         len = new->a_vals[0].bv_len;
3371                                                 rc = memcmp( old->a_vals[0].bv_val,
3372                                                         new->a_vals[0].bv_val, len );
3373                                                 if ( rc > 0 ) {
3374                                                         Debug( LDAP_DEBUG_SYNC,
3375                                                                 "dn_callback : new entry is older than ours "
3376                                                                 "%s ours %s, new %s\n",
3377                                                                 rs->sr_entry->e_name.bv_val,
3378                                                                 old->a_vals[0].bv_val,
3379                                                                 new->a_vals[0].bv_val );
3380                                                         return LDAP_SUCCESS;
3381                                                 } else if ( rc == 0 ) {
3382                                                         Debug( LDAP_DEBUG_SYNC,
3383                                                                 "dn_callback : entries have identical CSN "
3384                                                                 "%s %s\n",
3385                                                                 rs->sr_entry->e_name.bv_val,
3386                                                                 old->a_vals[0].bv_val, 0 );
3387                                                         return LDAP_SUCCESS;
3388                                                 }
3389                                         }
3390                                 }
3391
3392                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
3393                                         &op->o_bd->be_nsuffix[0] );
3394
3395                                 /* Did the DN change?
3396                                  * case changes in the parent are ignored,
3397                                  * we only want to know if the RDN was
3398                                  * actually changed.
3399                                  */
3400                                 dnRdn( &rs->sr_entry->e_name, &old_rdn );
3401                                 dnRdn( &dni->new_entry->e_name, &new_rdn );
3402                                 dnParent( &rs->sr_entry->e_nname, &old_p );
3403                                 dnParent( &dni->new_entry->e_nname, &new_p );
3404
3405                                 new_sup = !dn_match( &old_p, &new_p );
3406                                 if ( !dn_match( &old_rdn, &new_rdn ) || new_sup )
3407                                 {
3408                                         struct berval oldRDN, oldVal;
3409                                         AttributeDescription *ad = NULL;
3410                                         int oldpos, newpos;
3411                                         Attribute *a;
3412
3413                                         dni->renamed = 1;
3414                                         if ( new_sup )
3415                                                 dni->nnewSup = new_p;
3416
3417                                         /* See if the oldRDN was deleted */
3418                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
3419                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
3420                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
3421                                                 oldRDN.bv_val );
3422                                         oldRDN.bv_len -= oldVal.bv_len + 1;
3423                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
3424                                         dni->oldDesc = ad;
3425                                         for ( oldpos=0, a=rs->sr_entry->e_attrs;
3426                                                 a && a->a_desc != ad; oldpos++, a=a->a_next );
3427                                         dni->oldNattr = a;
3428                                         for ( newpos=0, a=dni->new_entry->e_attrs;
3429                                                 a && a->a_desc != ad; newpos++, a=a->a_next );
3430                                         if ( !a || oldpos != newpos || attr_valfind( a,
3431                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
3432                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
3433                                                 SLAP_MR_VALUE_OF_SYNTAX,
3434                                                 &oldVal, NULL, op->o_tmpmemctx ) != LDAP_SUCCESS )
3435                                         {
3436                                                 dni->delOldRDN = 1;
3437                                         }
3438                                         /* Get the newRDN's desc */
3439                                         dnRdn( &dni->new_entry->e_nname, &oldRDN );
3440                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=');
3441                                         oldRDN.bv_len = oldVal.bv_val - oldRDN.bv_val;
3442                                         ad = NULL;
3443                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
3444                                         dni->newDesc = ad;
3445
3446                                         /* A ModDN has happened, but in Refresh mode other
3447                                          * changes may have occurred before we picked it up.
3448                                          * So fallthru to regular Modify processing.
3449                                          */
3450                                 }
3451
3452                                 syncrepl_diff_entry( op, rs->sr_entry->e_attrs,
3453                                         dni->new_entry->e_attrs, &dni->mods, dni->modlist,
3454                                         is_ctx );
3455                         }
3456                 }
3457         } else if ( rs->sr_type == REP_RESULT ) {
3458                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
3459                         Debug( LDAP_DEBUG_ANY,
3460                                 "dn_callback : consistency error - "
3461                                 "entryUUID is not unique\n", 0, 0, 0 );
3462                 }
3463         }
3464
3465         return LDAP_SUCCESS;
3466 }
3467
3468 static int
3469 nonpresent_callback(
3470         Operation*      op,
3471         SlapReply*      rs )
3472 {
3473         syncinfo_t *si = op->o_callback->sc_private;
3474         Attribute *a;
3475         int count = 0;
3476         struct berval* present_uuid = NULL;
3477         struct nonpresent_entry *np_entry;
3478
3479         if ( rs->sr_type == REP_RESULT ) {
3480                 count = avl_free( si->si_presentlist, ch_free );
3481                 si->si_presentlist = NULL;
3482
3483         } else if ( rs->sr_type == REP_SEARCH ) {
3484                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
3485                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
3486
3487                         if ( a ) {
3488                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
3489                                         syncuuid_cmp );
3490                         }
3491
3492                         if ( LogTest( LDAP_DEBUG_SYNC ) ) {
3493                                 char buf[sizeof("rid=999 non")];
3494
3495                                 snprintf( buf, sizeof(buf), "%s %s", si->si_ridtxt,
3496                                         present_uuid ? "" : "non" );
3497
3498                                 Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %spresent UUID %s, dn %s\n",
3499                                         buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
3500                         }
3501
3502                         if ( a == NULL ) return 0;
3503                 }
3504
3505                 if ( present_uuid == NULL ) {
3506                         np_entry = (struct nonpresent_entry *)
3507                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
3508                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
3509                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
3510                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
3511
3512                 } else {
3513                         avl_delete( &si->si_presentlist,
3514                                 &a->a_nvals[0], syncuuid_cmp );
3515                         ch_free( present_uuid );
3516                 }
3517         }
3518         return LDAP_SUCCESS;
3519 }
3520
3521 static int
3522 null_callback(
3523         Operation*      op,
3524         SlapReply*      rs )
3525 {
3526         if ( rs->sr_err != LDAP_SUCCESS &&
3527                 rs->sr_err != LDAP_REFERRAL &&
3528                 rs->sr_err != LDAP_ALREADY_EXISTS &&
3529                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
3530                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
3531         {
3532                 Debug( LDAP_DEBUG_ANY,
3533                         "null_callback : error code 0x%x\n",
3534                         rs->sr_err, 0, 0 );
3535         }
3536         return LDAP_SUCCESS;
3537 }
3538
3539 static struct berval *
3540 slap_uuidstr_from_normalized(
3541         struct berval* uuidstr,
3542         struct berval* normalized,
3543         void *ctx )
3544 {
3545 #if 0
3546         struct berval *new;
3547         unsigned char nibble;
3548         int i, d = 0;
3549
3550         if ( normalized == NULL ) return NULL;
3551         if ( normalized->bv_len != 16 ) return NULL;
3552
3553         if ( uuidstr ) {
3554                 new = uuidstr;
3555         } else {
3556                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3557                 if ( new == NULL ) {
3558                         return NULL;
3559                 }
3560         }
3561
3562         new->bv_len = 36;
3563
3564         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3565                 if ( new != uuidstr ) {
3566                         slap_sl_free( new, ctx );
3567                 }
3568                 return NULL;
3569         }
3570
3571         for ( i = 0; i < 16; i++ ) {
3572                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
3573                         new->bv_val[(i<<1)+d] = '-';
3574                         d += 1;
3575                 }
3576
3577                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
3578                 if ( nibble < 10 ) {
3579                         new->bv_val[(i<<1)+d] = nibble + '0';
3580                 } else {
3581                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
3582                 }
3583
3584                 nibble = (normalized->bv_val[i]) & 0xF;
3585                 if ( nibble < 10 ) {
3586                         new->bv_val[(i<<1)+d+1] = nibble + '0';
3587                 } else {
3588                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
3589                 }
3590         }
3591
3592         new->bv_val[new->bv_len] = '\0';
3593         return new;
3594 #endif
3595
3596         struct berval   *new;
3597         int             rc = 0;
3598
3599         if ( normalized == NULL ) return NULL;
3600         if ( normalized->bv_len != 16 ) return NULL;
3601
3602         if ( uuidstr ) {
3603                 new = uuidstr;
3604
3605         } else {
3606                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3607                 if ( new == NULL ) {
3608                         return NULL;
3609                 }
3610         }
3611
3612         new->bv_len = 36;
3613
3614         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3615                 rc = 1;
3616                 goto done;
3617         }
3618
3619         rc = lutil_uuidstr_from_normalized( normalized->bv_val,
3620                 normalized->bv_len, new->bv_val, new->bv_len + 1 );
3621
3622 done:;
3623         if ( rc == -1 ) {
3624                 if ( new != NULL ) {
3625                         if ( new->bv_val != NULL ) {
3626                                 slap_sl_free( new->bv_val, ctx );
3627                         }
3628
3629                         if ( new != uuidstr ) {
3630                                 slap_sl_free( new, ctx );
3631                         }
3632                 }
3633                 new = NULL;
3634
3635         } else {
3636                 new->bv_len = rc;
3637         }
3638
3639         return new;
3640 }
3641
3642 static int
3643 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
3644 {
3645         const struct berval *uuid1 = v_uuid1;
3646         const struct berval *uuid2 = v_uuid2;
3647         int rc = uuid1->bv_len - uuid2->bv_len;
3648         if ( rc ) return rc;
3649         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
3650 }
3651
3652 void
3653 syncinfo_free( syncinfo_t *sie, int free_all )
3654 {
3655         syncinfo_t *si_next;
3656
3657         Debug( LDAP_DEBUG_TRACE, "syncinfo_free: %s\n",
3658                 sie->si_ridtxt, 0, 0 );
3659
3660         do {
3661                 si_next = sie->si_next;
3662
3663                 if ( sie->si_ld ) {
3664                         if ( sie->si_conn ) {
3665                                 connection_client_stop( sie->si_conn );
3666                                 sie->si_conn = NULL;
3667                         }
3668                         ldap_unbind_ext( sie->si_ld, NULL, NULL );
3669                 }
3670         
3671                 if ( sie->si_re ) {
3672                         struct re_s             *re = sie->si_re;
3673                         sie->si_re = NULL;
3674
3675                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3676                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
3677                                 ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3678                         ldap_pvt_runqueue_remove( &slapd_rq, re );
3679                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3680                 }
3681
3682                 ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
3683
3684                 bindconf_free( &sie->si_bindconf );
3685
3686                 if ( sie->si_filterstr.bv_val ) {
3687                         ch_free( sie->si_filterstr.bv_val );
3688                 }
3689                 if ( sie->si_logfilterstr.bv_val ) {
3690                         ch_free( sie->si_logfilterstr.bv_val );
3691                 }
3692                 if ( sie->si_base.bv_val ) {
3693                         ch_free( sie->si_base.bv_val );
3694                 }
3695                 if ( sie->si_logbase.bv_val ) {
3696                         ch_free( sie->si_logbase.bv_val );
3697                 }
3698                 if ( sie->si_attrs ) {
3699                         int i = 0;
3700                         while ( sie->si_attrs[i] != NULL ) {
3701                                 ch_free( sie->si_attrs[i] );
3702                                 i++;
3703                         }
3704                         ch_free( sie->si_attrs );
3705                 }
3706                 if ( sie->si_exattrs ) {
3707                         int i = 0;
3708                         while ( sie->si_exattrs[i] != NULL ) {
3709                                 ch_free( sie->si_exattrs[i] );
3710                                 i++;
3711                         }
3712                         ch_free( sie->si_exattrs );
3713                 }
3714                 if ( sie->si_anlist ) {
3715                         int i = 0;
3716                         while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
3717                                 ch_free( sie->si_anlist[i].an_name.bv_val );
3718                                 i++;
3719                         }
3720                         ch_free( sie->si_anlist );
3721                 }
3722                 if ( sie->si_exanlist ) {
3723                         int i = 0;
3724                         while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
3725                                 ch_free( sie->si_exanlist[i].an_name.bv_val );
3726                                 i++;
3727                         }
3728                         ch_free( sie->si_exanlist );
3729                 }
3730                 if ( sie->si_retryinterval ) {
3731                         ch_free( sie->si_retryinterval );
3732                 }
3733                 if ( sie->si_retrynum ) {
3734                         ch_free( sie->si_retrynum );
3735                 }
3736                 if ( sie->si_retrynum_init ) {
3737                         ch_free( sie->si_retrynum_init );
3738                 }
3739                 slap_sync_cookie_free( &sie->si_syncCookie, 0 );
3740                 if ( sie->si_presentlist ) {
3741                     avl_free( sie->si_presentlist, ch_free );
3742                 }
3743                 while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
3744                         struct nonpresent_entry* npe;
3745                         npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
3746                         LDAP_LIST_REMOVE( npe, npe_link );
3747                         if ( npe->npe_name ) {
3748                                 if ( npe->npe_name->bv_val ) {
3749                                         ch_free( npe->npe_name->bv_val );
3750                                 }
3751                                 ch_free( npe->npe_name );
3752                         }
3753                         if ( npe->npe_nname ) {
3754                                 if ( npe->npe_nname->bv_val ) {
3755                                         ch_free( npe->npe_nname->bv_val );
3756                                 }
3757                                 ch_free( npe->npe_nname );
3758                         }
3759                         ch_free( npe );
3760                 }
3761                 if ( sie->si_cookieState ) {
3762                         sie->si_cookieState->cs_ref--;
3763                         if ( !sie->si_cookieState->cs_ref ) {
3764                                 ch_free( sie->si_cookieState->cs_sids );
3765                                 ber_bvarray_free( sie->si_cookieState->cs_vals );
3766                                 ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
3767                                 ch_free( sie->si_cookieState );
3768                         }
3769                 }
3770                 ch_free( sie );
3771                 sie = si_next;
3772         } while ( free_all && si_next );
3773 }
3774
3775
3776
3777 /* NOTE: used & documented in slapd.conf(5) */
3778 #define IDSTR                   "rid"
3779 #define PROVIDERSTR             "provider"
3780 #define SCHEMASTR               "schemachecking"
3781 #define FILTERSTR               "filter"
3782 #define SEARCHBASESTR           "searchbase"
3783 #define SCOPESTR                "scope"
3784 #define ATTRSONLYSTR            "attrsonly"
3785 #define ATTRSSTR                "attrs"
3786 #define TYPESTR                 "type"
3787 #define INTERVALSTR             "interval"
3788 #define RETRYSTR                "retry"
3789 #define SLIMITSTR               "sizelimit"
3790 #define TLIMITSTR               "timelimit"
3791 #define SYNCDATASTR             "syncdata"
3792 #define LOGBASESTR              "logbase"
3793 #define LOGFILTERSTR    "logfilter"
3794
3795 /* FIXME: undocumented */
3796 #define EXATTRSSTR              "exattrs"
3797 #define MANAGEDSAITSTR          "manageDSAit"
3798
3799 /* mandatory */
3800 enum {
3801         GOT_RID                 = 0x00000001U,
3802         GOT_PROVIDER            = 0x00000002U,
3803         GOT_SCHEMACHECKING      = 0x00000004U,
3804         GOT_FILTER              = 0x00000008U,
3805         GOT_SEARCHBASE          = 0x00000010U,
3806         GOT_SCOPE               = 0x00000020U,
3807         GOT_ATTRSONLY           = 0x00000040U,
3808         GOT_ATTRS               = 0x00000080U,
3809         GOT_TYPE                = 0x00000100U,
3810         GOT_INTERVAL            = 0x00000200U,
3811         GOT_RETRY               = 0x00000400U,
3812         GOT_SLIMIT              = 0x00000800U,
3813         GOT_TLIMIT              = 0x00001000U,
3814         GOT_SYNCDATA            = 0x00002000U,
3815         GOT_LOGBASE             = 0x00004000U,
3816         GOT_LOGFILTER           = 0x00008000U,
3817         GOT_EXATTRS             = 0x00010000U,
3818         GOT_MANAGEDSAIT         = 0x00020000U,
3819         GOT_BINDCONF            = 0x00040000U,
3820
3821 /* check */
3822         GOT_REQUIRED            = (GOT_RID|GOT_PROVIDER|GOT_SEARCHBASE)
3823 };
3824
3825 static slap_verbmasks datamodes[] = {
3826         { BER_BVC("default"), SYNCDATA_DEFAULT },
3827         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
3828         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
3829         { BER_BVNULL, 0 }
3830 };
3831
3832 static int
3833 parse_syncrepl_retry(
3834         ConfigArgs      *c,
3835         char            *arg,
3836         syncinfo_t      *si )
3837 {
3838         char **retry_list;
3839         int j, k, n;
3840         int use_default = 0;
3841
3842         char *val = arg + STRLENOF( RETRYSTR "=" );
3843         if ( strcasecmp( val, "undefined" ) == 0 ) {
3844                 val = "3600 +";
3845                 use_default = 1;
3846         }
3847
3848         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
3849         retry_list[0] = NULL;
3850
3851         slap_str2clist( &retry_list, val, " ,\t" );
3852
3853         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3854         n = k / 2;
3855         if ( k % 2 ) {
3856                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3857                         "Error: incomplete syncrepl retry list" );
3858                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3859                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3860                         ch_free( retry_list[k] );
3861                 }
3862                 ch_free( retry_list );
3863                 return 1;
3864         }
3865         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
3866         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
3867         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
3868         for ( j = 0; j < n; j++ ) {
3869                 unsigned long   t;
3870                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3871                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3872                                 "Error: invalid retry interval \"%s\" (#%d)",
3873                                 retry_list[j*2], j );
3874                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3875                         /* do some cleanup */
3876                         return 1;
3877                 }
3878                 si->si_retryinterval[j] = (time_t)t;
3879                 if ( *retry_list[j*2+1] == '+' ) {
3880                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3881                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3882                         j++;
3883                         break;
3884                 } else {
3885                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3886                                         || si->si_retrynum_init[j] <= 0 )
3887                         {
3888                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3889                                         "Error: invalid initial retry number \"%s\" (#%d)",
3890                                         retry_list[j*2+1], j );
3891                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3892                                 /* do some cleanup */
3893                                 return 1;
3894                         }
3895                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3896                                         || si->si_retrynum[j] <= 0 )
3897                         {
3898                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3899                                         "Error: invalid retry number \"%s\" (#%d)",
3900                                         retry_list[j*2+1], j );
3901                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3902                                 /* do some cleanup */
3903                                 return 1;
3904                         }
3905                 }
3906         }
3907         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3908         si->si_retrynum[j] = RETRYNUM_TAIL;
3909         si->si_retryinterval[j] = 0;
3910         
3911         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3912                 ch_free( retry_list[k] );
3913         }
3914         ch_free( retry_list );
3915         if ( !use_default ) {
3916                 si->si_got |= GOT_RETRY;
3917         }
3918
3919         return 0;
3920 }
3921
3922 static int
3923 parse_syncrepl_line(
3924         ConfigArgs      *c,
3925         syncinfo_t      *si )
3926 {
3927         int     i;
3928         char    *val;
3929
3930         for ( i = 1; i < c->argc; i++ ) {
3931                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
3932                                         STRLENOF( IDSTR "=" ) ) )
3933                 {
3934                         int tmp;
3935                         /* '\0' string terminator accounts for '=' */
3936                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
3937                         if ( lutil_atoi( &tmp, val ) != 0 ) {
3938                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3939                                         "Error: parse_syncrepl_line: "
3940                                         "unable to parse syncrepl id \"%s\"", val );
3941                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3942                                 return -1;
3943                         }
3944                         if ( tmp > SLAP_SYNC_SID_MAX || tmp < 0 ) {
3945                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3946                                         "Error: parse_syncrepl_line: "
3947                                         "syncrepl id %d is out of range [0..4095]", tmp );
3948                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3949                                 return -1;
3950                         }
3951                         si->si_rid = tmp;
3952                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
3953                         si->si_got |= GOT_RID;
3954                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
3955                                         STRLENOF( PROVIDERSTR "=" ) ) )
3956                 {
3957                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
3958                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
3959                         si->si_got |= GOT_PROVIDER;
3960                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
3961                                         STRLENOF( SCHEMASTR "=" ) ) )
3962                 {
3963                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
3964                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
3965                                 si->si_schemachecking = 1;
3966                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
3967                                 si->si_schemachecking = 0;
3968                         } else {
3969                                 si->si_schemachecking = 1;
3970                         }
3971                         si->si_got |= GOT_SCHEMACHECKING;
3972                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
3973                                         STRLENOF( FILTERSTR "=" ) ) )
3974                 {
3975                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
3976                         if ( si->si_filterstr.bv_val )
3977                                 ch_free( si->si_filterstr.bv_val );
3978                         ber_str2bv( val, 0, 1, &si->si_filterstr );
3979                         si->si_got |= GOT_FILTER;
3980                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
3981                                         STRLENOF( LOGFILTERSTR "=" ) ) )
3982                 {
3983                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
3984                         if ( si->si_logfilterstr.bv_val )
3985                                 ch_free( si->si_logfilterstr.bv_val );
3986                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
3987                         si->si_got |= GOT_LOGFILTER;
3988                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
3989                                         STRLENOF( SEARCHBASESTR "=" ) ) )
3990                 {
3991                         struct berval   bv;
3992                         int             rc;
3993
3994                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
3995                         if ( si->si_base.bv_val ) {
3996                                 ch_free( si->si_base.bv_val );
3997                         }
3998                         ber_str2bv( val, 0, 0, &bv );
3999                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
4000                         if ( rc != LDAP_SUCCESS ) {
4001                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4002                                         "Invalid base DN \"%s\": %d (%s)",
4003                                         val, rc, ldap_err2string( rc ) );
4004                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4005                                 return -1;
4006                         }
4007                         if ( !be_issubordinate( c->be, &si->si_base ) ) {
4008                                 ch_free( si->si_base.bv_val );
4009                                 BER_BVZERO( &si->si_base );
4010                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4011                                         "Base DN \"%s\" is not within the database naming context",
4012                                         val );
4013                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4014                                 return -1;
4015                         }
4016                         si->si_got |= GOT_SEARCHBASE;
4017                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
4018                                         STRLENOF( LOGBASESTR "=" ) ) )
4019                 {
4020                         struct berval   bv;
4021                         int             rc;
4022
4023                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
4024                         if ( si->si_logbase.bv_val ) {
4025                                 ch_free( si->si_logbase.bv_val );
4026                         }
4027                         ber_str2bv( val, 0, 0, &bv );
4028                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
4029                         if ( rc != LDAP_SUCCESS ) {
4030                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4031                                         "Invalid logbase DN \"%s\": %d (%s)",
4032                                         val, rc, ldap_err2string( rc ) );
4033                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4034                                 return -1;
4035                         }
4036                         si->si_got |= GOT_LOGBASE;
4037                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
4038                                         STRLENOF( SCOPESTR "=" ) ) )
4039                 {
4040                         int j;
4041                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
4042                         j = ldap_pvt_str2scope( val );
4043                         if ( j < 0 ) {
4044                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4045                                         "Error: parse_syncrepl_line: "
4046                                         "unknown scope \"%s\"", val);
4047                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4048                                 return -1;
4049                         }
4050                         si->si_scope = j;
4051                         si->si_got |= GOT_SCOPE;
4052                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
4053                                         STRLENOF( ATTRSONLYSTR ) ) )
4054                 {
4055                         si->si_attrsonly = 1;
4056                         si->si_got |= GOT_ATTRSONLY;
4057                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
4058                                         STRLENOF( ATTRSSTR "=" ) ) )
4059                 {
4060                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
4061                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4062                                 char *attr_fname;
4063                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
4064                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
4065                                 if ( si->si_anlist == NULL ) {
4066                                         ch_free( attr_fname );
4067                                         return -1;
4068                                 }
4069                                 si->si_anfile = attr_fname;
4070                         } else {
4071                                 char *str, *s, *next;
4072                                 const char *delimstr = " ,\t";
4073                                 str = ch_strdup( val );
4074                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
4075                                                 s != NULL;
4076                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
4077                                 {
4078                                         if ( strlen(s) == 1 && *s == '*' ) {
4079                                                 si->si_allattrs = 1;
4080                                                 val[ s - str ] = delimstr[0];
4081                                         }
4082                                         if ( strlen(s) == 1 && *s == '+' ) {
4083                                                 si->si_allopattrs = 1;
4084                                                 val [ s - str ] = delimstr[0];
4085                                         }
4086                                 }
4087                                 ch_free( str );
4088                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
4089                                 if ( si->si_anlist == NULL ) {
4090                                         return -1;
4091                                 }
4092                         }
4093                         si->si_got |= GOT_ATTRS;
4094                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
4095                                         STRLENOF( EXATTRSSTR "=" ) ) )
4096                 {
4097                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
4098                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4099                                 char *attr_fname;
4100                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
4101                                 si->si_exanlist = file2anlist(
4102                                         si->si_exanlist, attr_fname, " ,\t" );
4103                                 if ( si->si_exanlist == NULL ) {
4104                                         ch_free( attr_fname );
4105                                         return -1;
4106                                 }
4107                                 ch_free( attr_fname );
4108                         } else {
4109                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
4110                                 if ( si->si_exanlist == NULL ) {
4111                                         return -1;
4112                                 }
4113                         }
4114                         si->si_got |= GOT_EXATTRS;
4115                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
4116                                         STRLENOF( TYPESTR "=" ) ) )
4117                 {
4118                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
4119                         if ( !strncasecmp( val, "refreshOnly",
4120                                                 STRLENOF("refreshOnly") ) )
4121                         {
4122                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4123                         } else if ( !strncasecmp( val, "refreshAndPersist",
4124                                                 STRLENOF("refreshAndPersist") ) )
4125                         {
4126                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
4127                                 si->si_interval = 60;
4128                         } else {
4129                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4130                                         "Error: parse_syncrepl_line: "
4131                                         "unknown sync type \"%s\"", val);
4132                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4133                                 return -1;
4134                         }
4135                         si->si_got |= GOT_TYPE;
4136                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
4137                                         STRLENOF( INTERVALSTR "=" ) ) )
4138                 {
4139                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
4140                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
4141                                 si->si_interval = 0;
4142                         } else if ( strchr( val, ':' ) != NULL ) {
4143                                 char *next, *ptr = val;
4144                                 int dd, hh, mm, ss;
4145
4146                                 dd = strtol( ptr, &next, 10 );
4147                                 if ( next == ptr || next[0] != ':' || dd < 0 ) {
4148                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4149                                                 "Error: parse_syncrepl_line: "
4150                                                 "invalid interval \"%s\", unable to parse days", val );
4151                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4152                                         return -1;
4153                                 }
4154                                 ptr = next + 1;
4155                                 hh = strtol( ptr, &next, 10 );
4156                                 if ( next == ptr || next[0] != ':' || hh < 0 || hh > 24 ) {
4157                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4158                                                 "Error: parse_syncrepl_line: "
4159                                                 "invalid interval \"%s\", unable to parse hours", val );
4160                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4161                                         return -1;
4162                                 }
4163                                 ptr = next + 1;
4164                                 mm = strtol( ptr, &next, 10 );
4165                                 if ( next == ptr || next[0] != ':' || mm < 0 || mm > 60 ) {
4166                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4167                                                 "Error: parse_syncrepl_line: "
4168                                                 "invalid interval \"%s\", unable to parse minutes", val );
4169                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4170                                         return -1;
4171                                 }
4172                                 ptr = next + 1;
4173                                 ss = strtol( ptr, &next, 10 );
4174                                 if ( next == ptr || next[0] != '\0' || ss < 0 || ss > 60 ) {
4175                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4176                                                 "Error: parse_syncrepl_line: "
4177                                                 "invalid interval \"%s\", unable to parse seconds", val );
4178                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4179                                         return -1;
4180                                 }
4181                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
4182                         } else {
4183                                 unsigned long   t;
4184
4185                                 if ( lutil_parse_time( val, &t ) != 0 ) {
4186                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4187                                                 "Error: parse_syncrepl_line: "
4188                                                 "invalid interval \"%s\"", val );
4189                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4190                                         return -1;
4191                                 }
4192                                 si->si_interval = (time_t)t;
4193                         }
4194                         if ( si->si_interval < 0 ) {
4195                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4196                                         "Error: parse_syncrepl_line: "
4197                                         "invalid interval \"%ld\"",
4198                                         (long) si->si_interval);
4199                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4200                                 return -1;
4201                         }
4202                         si->si_got |= GOT_INTERVAL;
4203                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
4204                                         STRLENOF( RETRYSTR "=" ) ) )
4205                 {
4206                         if ( parse_syncrepl_retry( c, c->argv[ i ], si ) ) {
4207                                 return 1;
4208                         }
4209                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
4210                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
4211                 {
4212                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
4213                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
4214                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
4215                         {
4216                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4217                                         "invalid manageDSAit value \"%s\".\n",
4218                                         val );
4219                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4220                                 return 1;
4221                         }
4222                         si->si_got |= GOT_MANAGEDSAIT;
4223                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
4224                                         STRLENOF( SLIMITSTR "=") ) )
4225                 {
4226                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
4227                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
4228                                 si->si_slimit = 0;
4229
4230                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
4231                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4232                                         "invalid size limit value \"%s\".\n",
4233                                         val );
4234                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4235                                 return 1;
4236                         }
4237                         si->si_got |= GOT_SLIMIT;
4238                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
4239                                         STRLENOF( TLIMITSTR "=" ) ) )
4240                 {
4241                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
4242                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
4243                                 si->si_tlimit = 0;
4244
4245                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
4246                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4247                                         "invalid time limit value \"%s\".\n",
4248                                         val );
4249                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4250                                 return 1;
4251                         }
4252                         si->si_got |= GOT_TLIMIT;
4253                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
4254                                         STRLENOF( SYNCDATASTR "=" ) ) )
4255                 {
4256                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
4257                         si->si_syncdata = verb_to_mask( val, datamodes );
4258                         si->si_got |= GOT_SYNCDATA;
4259                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
4260                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4261                                 "Error: parse_syncrepl_line: "
4262                                 "unable to parse \"%s\"\n", c->argv[ i ] );
4263                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4264                         return -1;
4265                 }
4266                 si->si_got |= GOT_BINDCONF;
4267         }
4268
4269         if ( ( si->si_got & GOT_REQUIRED ) != GOT_REQUIRED ) {
4270                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4271                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
4272                         si->si_got & GOT_RID ? "" : " "IDSTR,
4273                         si->si_got & GOT_PROVIDER ? "" : " "PROVIDERSTR,
4274                         si->si_got & GOT_SEARCHBASE ? "" : " "SEARCHBASESTR );
4275                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4276                 return -1;
4277         }
4278
4279         if ( !( si->si_got & GOT_RETRY ) ) {
4280                 Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": no retry defined, using default\n", 
4281                         si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", 0 );
4282                 if ( si->si_retryinterval == NULL ) {
4283                         if ( parse_syncrepl_retry( c, "retry=undefined", si ) ) {
4284                                 return 1;
4285                         }
4286                 }
4287         }
4288
4289         return 0;
4290 }
4291
4292 static int
4293 add_syncrepl(
4294         ConfigArgs *c )
4295 {
4296         syncinfo_t *si;
4297         int     rc = 0;
4298
4299         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
4300                 snprintf( c->cr_msg, sizeof(c->cr_msg), "database %s does not support "
4301                         "operations required for syncrepl", c->be->be_type );
4302                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
4303                 return 1;
4304         }
4305         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
4306                 strcpy( c->cr_msg, "rootDN must be defined before syncrepl may be used" );
4307                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
4308                 return 1;
4309         }
4310         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
4311
4312         if ( si == NULL ) {
4313                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
4314                 return 1;
4315         }
4316
4317         si->si_bindconf.sb_tls = SB_TLS_OFF;
4318         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
4319         si->si_schemachecking = 0;
4320         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
4321                 &si->si_filterstr );
4322         si->si_base.bv_val = NULL;
4323         si->si_scope = LDAP_SCOPE_SUBTREE;
4324         si->si_attrsonly = 0;
4325         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
4326         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
4327         si->si_attrs = NULL;
4328         si->si_allattrs = 0;
4329         si->si_allopattrs = 0;
4330         si->si_exattrs = NULL;
4331         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4332         si->si_interval = 86400;
4333         si->si_retryinterval = NULL;
4334         si->si_retrynum_init = NULL;
4335         si->si_retrynum = NULL;
4336         si->si_manageDSAit = 0;
4337         si->si_tlimit = 0;
4338         si->si_slimit = 0;
4339
4340         si->si_presentlist = NULL;
4341         LDAP_LIST_INIT( &si->si_nonpresentlist );
4342         ldap_pvt_thread_mutex_init( &si->si_mutex );
4343
4344         rc = parse_syncrepl_line( c, si );
4345
4346         if ( rc == 0 ) {
4347                 LDAPURLDesc *lud;
4348
4349                 /* Must be LDAPv3 because we need controls */
4350                 switch ( si->si_bindconf.sb_version ) {
4351                 case 0:
4352                         /* not explicitly set */
4353                         si->si_bindconf.sb_version = LDAP_VERSION3;
4354                         break;
4355                 case 3:
4356                         /* explicitly set */
4357                         break;
4358                 default:
4359                         Debug( LDAP_DEBUG_ANY,
4360                                 "version %d incompatible with syncrepl\n",
4361                                 si->si_bindconf.sb_version, 0, 0 );
4362                         syncinfo_free( si, 0 ); 
4363                         return 1;
4364                 }
4365
4366                 if ( ldap_url_parse( si->si_bindconf.sb_uri.bv_val, &lud )) {
4367                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4368                                 "<%s> invalid URL", c->argv[0] );
4369                         Debug( LDAP_DEBUG_ANY, "%s: %s %s\n",
4370                                 c->log, c->cr_msg, si->si_bindconf.sb_uri.bv_val );
4371                         return 1;
4372                 }
4373
4374                 si->si_be = c->be;
4375                 if ( slapMode & SLAP_SERVER_MODE ) {
4376                         int isMe = 0;
4377                         /* check if consumer points to current server and database.
4378                          * If so, ignore this configuration.
4379                          */
4380                         if ( !SLAP_DBHIDDEN( c->be ) ) {
4381                                 int i;
4382                                 /* if searchbase doesn't match current DB suffix,
4383                                  * assume it's different
4384                                  */
4385                                 for ( i=0; !BER_BVISNULL( &c->be->be_nsuffix[i] ); i++ ) {
4386                                         if ( bvmatch( &si->si_base, &c->be->be_nsuffix[i] )) {
4387                                                 isMe = 1;
4388                                                 break;
4389                                         }
4390                                 }
4391                                 /* if searchbase matches, see if URLs match */
4392                                 if ( isMe && config_check_my_url( si->si_bindconf.sb_uri.bv_val,
4393                                                 lud ) == NULL )
4394                                         isMe = 0;
4395                         }
4396
4397                         if ( !isMe ) {
4398                                 init_syncrepl( si );
4399                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4400                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
4401                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
4402                                         si->si_ridtxt );
4403                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4404                                 if ( si->si_re )
4405                                         rc = config_sync_shadow( c ) ? -1 : 0;
4406                                 else
4407                                         rc = -1;
4408                         }
4409                 } else {
4410                         /* mirrormode still needs to see this flag in tool mode */
4411                         rc = config_sync_shadow( c ) ? -1 : 0;
4412                 }
4413                 ldap_free_urldesc( lud );
4414         }
4415
4416 #ifdef HAVE_TLS
4417         /* Use main slapd defaults */
4418         bindconf_tls_defaults( &si->si_bindconf );
4419 #endif
4420         if ( rc < 0 ) {
4421                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
4422                 syncinfo_free( si, 0 ); 
4423                 return 1;
4424         } else {
4425                 Debug( LDAP_DEBUG_CONFIG,
4426                         "Config: ** successfully added syncrepl \"%s\"\n",
4427                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
4428                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
4429                 if ( c->be->be_syncinfo ) {
4430                         syncinfo_t *sip;
4431
4432                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
4433
4434                         /* add new syncrepl to end of list (same order as when deleting) */
4435                         for ( sip = c->be->be_syncinfo; sip->si_next; sip = sip->si_next );
4436                         sip->si_next = si;
4437                 } else {
4438                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
4439                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
4440
4441                         c->be->be_syncinfo = si;
4442                 }
4443                 si->si_cookieState->cs_ref++;
4444
4445                 si->si_next = NULL;
4446
4447                 return 0;
4448         }
4449 }
4450
4451 static void
4452 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
4453 {
4454         struct berval bc, uri, bs;
4455         char buf[BUFSIZ*2], *ptr;
4456         ber_len_t len;
4457         int i;
4458 #       define WHATSLEFT        ((ber_len_t) (&buf[sizeof( buf )] - ptr))
4459
4460         BER_BVZERO( bv );
4461
4462         /* temporarily inhibit bindconf from printing URI */
4463         uri = si->si_bindconf.sb_uri;
4464         BER_BVZERO( &si->si_bindconf.sb_uri );
4465         si->si_bindconf.sb_version = 0;
4466         bindconf_unparse( &si->si_bindconf, &bc );
4467         si->si_bindconf.sb_uri = uri;
4468         si->si_bindconf.sb_version = LDAP_VERSION3;
4469
4470         ptr = buf;
4471         assert( si->si_rid >= 0 && si->si_rid <= SLAP_SYNC_SID_MAX );
4472         len = snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
4473                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
4474         if ( len >= sizeof( buf ) ) return;
4475         ptr += len;
4476         if ( !BER_BVISNULL( &bc ) ) {
4477                 if ( WHATSLEFT <= bc.bv_len ) {
4478                         free( bc.bv_val );
4479                         return;
4480                 }
4481                 ptr = lutil_strcopy( ptr, bc.bv_val );
4482                 free( bc.bv_val );
4483         }
4484         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
4485                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
4486                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
4487                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
4488                 *ptr++ = '"';
4489         }
4490         if ( !BER_BVISNULL( &si->si_base ) ) {
4491                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
4492                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
4493                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
4494                 *ptr++ = '"';
4495         }
4496         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
4497                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
4498                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
4499                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
4500                 *ptr++ = '"';
4501         }
4502         if ( !BER_BVISNULL( &si->si_logbase ) ) {
4503                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
4504                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
4505                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
4506                 *ptr++ = '"';
4507         }
4508         if ( ldap_pvt_scope2bv( si->si_scope, &bs ) == LDAP_SUCCESS ) {
4509                 if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + bs.bv_len ) return;
4510                 ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
4511                 ptr = lutil_strcopy( ptr, bs.bv_val );
4512         }
4513         if ( si->si_attrsonly ) {
4514                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
4515                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
4516         }
4517         if ( si->si_anfile ) {
4518                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
4519                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
4520                 ptr = lutil_strcopy( ptr, si->si_anfile );
4521                 *ptr++ = '"';
4522         } else if ( si->si_allattrs || si->si_allopattrs ||
4523                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
4524         {
4525                 char *old;
4526
4527                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
4528                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
4529                 old = ptr;
4530                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
4531                 if ( ptr == NULL ) return;
4532                 if ( si->si_allattrs ) {
4533                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
4534                         if ( old != ptr ) *ptr++ = ',';
4535                         *ptr++ = '*';
4536                 }
4537                 if ( si->si_allopattrs ) {
4538                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
4539                         if ( old != ptr ) *ptr++ = ',';
4540                         *ptr++ = '+';
4541                 }
4542                 *ptr++ = '"';
4543         }
4544         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
4545                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
4546                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
4547                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
4548                 if ( ptr == NULL ) return;
4549         }
4550         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
4551         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
4552         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
4553         
4554         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
4555         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
4556         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
4557                 "refreshAndPersist" : "refreshOnly" );
4558
4559         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
4560                 int dd, hh, mm, ss;
4561
4562                 dd = si->si_interval;
4563                 ss = dd % 60;
4564                 dd /= 60;
4565                 mm = dd % 60;
4566                 dd /= 60;
4567                 hh = dd % 24;
4568                 dd /= 24;
4569                 len = snprintf( ptr, WHATSLEFT, " %s=%02d:%02d:%02d:%02d",
4570                         INTERVALSTR, dd, hh, mm, ss );
4571                 if ( len >= WHATSLEFT ) return;
4572                 ptr += len;
4573         }
4574
4575         if ( si->si_got & GOT_RETRY ) {
4576                 const char *space = "";
4577                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
4578                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
4579                 for (i=0; si->si_retryinterval[i]; i++) {
4580                         len = snprintf( ptr, WHATSLEFT, "%s%ld ", space,
4581                                 (long) si->si_retryinterval[i] );
4582                         space = " ";
4583                         if ( WHATSLEFT - 1 <= len ) return;
4584                         ptr += len;
4585                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
4586                                 *ptr++ = '+';
4587                         else {
4588                                 len = snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
4589                                 if ( WHATSLEFT <= len ) return;
4590                                 ptr += len;
4591                         }
4592                 }
4593                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
4594                 *ptr++ = '"';
4595         } else {
4596                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=undefined" );
4597         }
4598
4599         if ( si->si_slimit ) {
4600                 len = snprintf( ptr, WHATSLEFT, " " SLIMITSTR "=%d", si->si_slimit );
4601                 if ( WHATSLEFT <= len ) return;
4602                 ptr += len;
4603         }
4604
4605         if ( si->si_tlimit ) {
4606                 len = snprintf( ptr, WHATSLEFT, " " TLIMITSTR "=%d", si->si_tlimit );
4607                 if ( WHATSLEFT <= len ) return;
4608                 ptr += len;
4609         }
4610
4611         if ( si->si_syncdata ) {
4612                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
4613                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
4614                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
4615                         ptr = lutil_strcopy( ptr, bc.bv_val );
4616                 }
4617         }
4618         bc.bv_len = ptr - buf;
4619         bc.bv_val = buf;
4620         ber_dupbv( bv, &bc );
4621 }
4622
4623 int
4624 syncrepl_config( ConfigArgs *c )
4625 {
4626         if (c->op == SLAP_CONFIG_EMIT) {
4627                 if ( c->be->be_syncinfo ) {
4628                         struct berval bv;
4629                         syncinfo_t *si;
4630
4631                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
4632                                 syncrepl_unparse( si, &bv ); 
4633                                 ber_bvarray_add( &c->rvalue_vals, &bv );
4634                         }
4635                         return 0;
4636                 }
4637                 return 1;
4638         } else if ( c->op == LDAP_MOD_DELETE ) {
4639                 int isrunning = 0;
4640                 if ( c->be->be_syncinfo ) {
4641                         syncinfo_t *si, **sip;
4642                         int i;
4643
4644                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
4645                                 si = *sip;
4646                                 if ( c->valx == -1 || i == c->valx ) {
4647                                         *sip = si->si_next;
4648                                         /* If the task is currently active, we have to leave
4649                                          * it running. It will exit on its own. This will only
4650                                          * happen when running on the cn=config DB.
4651                                          */
4652                                         if ( si->si_re ) {
4653                                                 if ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
4654                                                         isrunning = 1;
4655                                                 } else {
4656                                                         if ( si->si_conn ) {
4657                                                                 /* If there's a persistent connection, it may
4658                                                                  * already have a thread queued. We know it's
4659                                                                  * not active, so it must be pending and we
4660                                                                  * can simply cancel it now.
4661                                                                  */
4662                                                                 ldap_pvt_thread_pool_retract( &connection_pool,
4663                                                                         si->si_re->routine, si->si_re );
4664                                                         }
4665                                                         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
4666                                                 }
4667                                         }
4668                                         if ( isrunning ) {
4669                                                 si->si_ctype = -1;
4670                                                 si->si_next = NULL;
4671                                         } else {
4672                                                 syncinfo_free( si, 0 );
4673                                         }
4674                                         if ( i == c->valx )
4675                                                 break;
4676                                 } else {
4677                                         sip = &si->si_next;
4678                                 }
4679                         }
4680                 }
4681                 if ( !c->be->be_syncinfo ) {
4682                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_SHADOW_MASK;
4683                 }
4684                 return 0;
4685         }
4686         if ( SLAP_SLURP_SHADOW( c->be ) ) {
4687                 Debug(LDAP_DEBUG_ANY, "%s: "
4688                         "syncrepl: database already shadowed.\n",
4689                         c->log, 0, 0);
4690                 return(1);
4691         } else {
4692                 return add_syncrepl( c );
4693         }
4694 }