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