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