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