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