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