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