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