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