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