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