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