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