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