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