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