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