]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
ITS#6054 quit using global malloc
[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-2009 The OpenLDAP Foundation.
6  * Portions Copyright 2003 by IBM Corporation.
7  * Portions Copyright 2003-2008 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 typedef struct cookie_state {
41         ldap_pvt_thread_mutex_t cs_mutex;
42         int     cs_num;
43         int cs_age;
44         int cs_ref;
45         struct berval *cs_vals;
46         int *cs_sids;
47 } cookie_state;
48         
49 #define SYNCDATA_DEFAULT        0       /* entries are plain LDAP entries */
50 #define SYNCDATA_ACCESSLOG      1       /* entries are accesslog format */
51 #define SYNCDATA_CHANGELOG      2       /* entries are changelog format */
52
53 #define SYNCLOG_LOGGING         0       /* doing a log-based update */
54 #define SYNCLOG_FALLBACK        1       /* doing a full refresh */
55
56 #define RETRYNUM_FOREVER        (-1)    /* retry forever */
57 #define RETRYNUM_TAIL           (-2)    /* end of retrynum array */
58 #define RETRYNUM_VALID(n)       ((n) >= RETRYNUM_FOREVER)       /* valid retrynum */
59 #define RETRYNUM_FINITE(n)      ((n) > RETRYNUM_FOREVER)        /* not forever */
60
61 typedef struct syncinfo_s {
62         struct syncinfo_s       *si_next;
63         BackendDB               *si_be;
64         BackendDB               *si_wbe;
65         struct re_s             *si_re;
66         int                     si_rid;
67         char                    si_ridtxt[ STRLENOF("rid=999") + 1 ];
68         slap_bindconf           si_bindconf;
69         struct berval           si_base;
70         struct berval           si_logbase;
71         struct berval           si_filterstr;
72         struct berval           si_logfilterstr;
73         int                     si_scope;
74         int                     si_attrsonly;
75         char                    *si_anfile;
76         AttributeName           *si_anlist;
77         AttributeName           *si_exanlist;
78         char                    **si_attrs;
79         char                    **si_exattrs;
80         int                     si_allattrs;
81         int                     si_allopattrs;
82         int                     si_schemachecking;
83         int                     si_type;        /* the active type */
84         int                     si_ctype;       /* the configured type */
85         time_t                  si_interval;
86         time_t                  *si_retryinterval;
87         int                     *si_retrynum_init;
88         int                     *si_retrynum;
89         struct sync_cookie      si_syncCookie;
90         cookie_state            *si_cookieState;
91         int                     si_cookieAge;
92         int                     si_manageDSAit;
93         int                     si_slimit;
94         int                     si_tlimit;
95         int                     si_refreshDelete;
96         int                     si_refreshPresent;
97         int                     si_refreshDone;
98         int                     si_syncdata;
99         int                     si_logstate;
100         int                     si_got;
101         ber_int_t       si_msgid;
102         Avlnode                 *si_presentlist;
103         LDAP                    *si_ld;
104         Connection              *si_conn;
105         LDAP_LIST_HEAD(np, nonpresent_entry)    si_nonpresentlist;
106         ldap_pvt_thread_mutex_t si_mutex;
107 } syncinfo_t;
108
109 static int syncuuid_cmp( const void *, const void * );
110 static int avl_presentlist_insert( syncinfo_t* si, struct berval *syncUUID );
111 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct sync_cookie *, int );
112 static int syncrepl_message_to_op(
113                                         syncinfo_t *, Operation *, LDAPMessage * );
114 static int syncrepl_message_to_entry(
115                                         syncinfo_t *, Operation *, LDAPMessage *,
116                                         Modifications **, Entry **, int );
117 static int syncrepl_entry(
118                                         syncinfo_t *, Operation*, Entry*,
119                                         Modifications**,int, struct berval*,
120                                         struct berval *cookieCSN );
121 static int syncrepl_updateCookie(
122                                         syncinfo_t *, Operation *, struct berval *,
123                                         struct sync_cookie * );
124 static struct berval * slap_uuidstr_from_normalized(
125                                         struct berval *, struct berval *, void * );
126
127 /* callback functions */
128 static int dn_callback( Operation *, SlapReply * );
129 static int nonpresent_callback( Operation *, SlapReply * );
130 static int null_callback( Operation *, SlapReply * );
131
132 static AttributeDescription *sync_descs[4];
133
134 static const char *
135 syncrepl_state2str( int state )
136 {
137         switch ( state ) {
138         case LDAP_SYNC_PRESENT:
139                 return "PRESENT";
140
141         case LDAP_SYNC_ADD:
142                 return "ADD";
143
144         case LDAP_SYNC_MODIFY:
145                 return "MODIFY";
146
147         case LDAP_SYNC_DELETE:
148                 return "DELETE";
149         }
150
151         return "UNKNOWN";
152 }
153
154 static void
155 init_syncrepl(syncinfo_t *si)
156 {
157         int i, j, k, l, n;
158         char **attrs, **exattrs;
159
160         if ( !sync_descs[0] ) {
161                 sync_descs[0] = slap_schema.si_ad_objectClass;
162                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
163                 sync_descs[2] = slap_schema.si_ad_entryCSN;
164                 sync_descs[3] = NULL;
165         }
166
167         if ( si->si_allattrs && si->si_allopattrs )
168                 attrs = NULL;
169         else
170                 attrs = anlist2attrs( si->si_anlist );
171
172         if ( attrs ) {
173                 if ( si->si_allattrs ) {
174                         i = 0;
175                         while ( attrs[i] ) {
176                                 if ( !is_at_operational( at_find( attrs[i] ) ) ) {
177                                         for ( j = i; attrs[j] != NULL; j++ ) {
178                                                 if ( j == i )
179                                                         ch_free( attrs[i] );
180                                                 attrs[j] = attrs[j+1];
181                                         }
182                                 } else {
183                                         i++;
184                                 }
185                         }
186                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
187                         attrs[i] = ch_strdup("*");
188                         attrs[i + 1] = NULL;
189
190                 } else if ( si->si_allopattrs ) {
191                         i = 0;
192                         while ( attrs[i] ) {
193                                 if ( is_at_operational( at_find( attrs[i] ) ) ) {
194                                         for ( j = i; attrs[j] != NULL; j++ ) {
195                                                 if ( j == i )
196                                                         ch_free( attrs[i] );
197                                                 attrs[j] = attrs[j+1];
198                                         }
199                                 } else {
200                                         i++;
201                                 }
202                         }
203                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
204                         attrs[i] = ch_strdup("+");
205                         attrs[i + 1] = NULL;
206                 }
207
208                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
209                         j = 0;
210                         while ( attrs[j] ) {
211                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
212                                         for ( k = j; attrs[k] != NULL; k++ ) {
213                                                 if ( k == j )
214                                                         ch_free( attrs[k] );
215                                                 attrs[k] = attrs[k+1];
216                                         }
217                                 } else {
218                                         j++;
219                                 }
220                         }
221                 }
222
223                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
224
225                 if ( si->si_allopattrs ) {
226                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ) );
227                 } else {
228                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ) );
229                 }
230
231                 /* Add Attributes */
232                 if ( si->si_allopattrs ) {
233                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
234                 } else {
235                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
236                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
237                         }
238                 }
239                 attrs[ n ] = NULL;
240
241         } else {
242
243                 i = 0;
244                 if ( si->si_allattrs == si->si_allopattrs ) {
245                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
246                         attrs[i++] = ch_strdup( "*" );
247                         attrs[i++] = ch_strdup( "+" );
248                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
249                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
250                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
251                         attrs[i++] = ch_strdup( "*" );
252                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
253                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
254                         }
255                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
256                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
257                         attrs[i++] = ch_strdup( "+" );
258                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
259                 }
260                 attrs[i] = NULL;
261         }
262         
263         si->si_attrs = attrs;
264
265         exattrs = anlist2attrs( si->si_exanlist );
266
267         if ( exattrs ) {
268                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
269
270                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
271                         j = 0;
272                         while ( exattrs[j] != NULL ) {
273                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
274                                         ch_free( exattrs[j] );
275                                         for ( k = j; exattrs[k] != NULL; k++ ) {
276                                                 exattrs[k] = exattrs[k+1];
277                                         }
278                                 } else {
279                                         j++;
280                                 }
281                         }
282                 }
283
284                 for ( i = 0; exattrs[i] != NULL; i++ ) {
285                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
286                                 ObjectClass     *oc;
287                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
288                                         k = 0;
289                                         while ( oc->soc_required[k] ) {
290                                                 if ( !strcmp( exattrs[i],
291                                                          oc->soc_required[k]->sat_cname.bv_val ) ) {
292                                                         ch_free( exattrs[i] );
293                                                         for ( l = i; exattrs[l]; l++ ) {
294                                                                 exattrs[l] = exattrs[l+1];
295                                                         }
296                                                 } else {
297                                                         k++;
298                                                 }
299                                         }
300                                 }
301                         }
302                 }
303
304                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
305
306                 if ( i != n )
307                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *) );
308         }
309
310         si->si_exattrs = exattrs;       
311 }
312
313 typedef struct logschema {
314         struct berval ls_dn;
315         struct berval ls_req;
316         struct berval ls_mod;
317         struct berval ls_newRdn;
318         struct berval ls_delRdn;
319         struct berval ls_newSup;
320 } logschema;
321
322 static logschema changelog_sc = {
323         BER_BVC("targetDN"),
324         BER_BVC("changeType"),
325         BER_BVC("changes"),
326         BER_BVC("newRDN"),
327         BER_BVC("deleteOldRDN"),
328         BER_BVC("newSuperior")
329 };
330
331 static logschema accesslog_sc = {
332         BER_BVC("reqDN"),
333         BER_BVC("reqType"),
334         BER_BVC("reqMod"),
335         BER_BVC("reqNewRDN"),
336         BER_BVC("reqDeleteOldRDN"),
337         BER_BVC("reqNewSuperior")
338 };
339
340 static int
341 ldap_sync_search(
342         syncinfo_t *si,
343         void *ctx )
344 {
345         BerElementBuffer berbuf;
346         BerElement *ber = (BerElement *)&berbuf;
347         LDAPControl c[3], *ctrls[4];
348         int rc;
349         int rhint;
350         char *base;
351         char **attrs, *lattrs[8];
352         char *filter;
353         int attrsonly;
354         int scope;
355
356         /* setup LDAP SYNC control */
357         ber_init2( ber, NULL, LBER_USE_DER );
358         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
359
360         /* If we're using a log but we have no state, then fallback to
361          * normal mode for a full refresh.
362          */
363         if ( si->si_syncdata && !si->si_syncCookie.numcsns ) {
364                 si->si_logstate = SYNCLOG_FALLBACK;
365         }
366
367         /* Use the log parameters if we're in log mode */
368         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
369                 logschema *ls;
370                 if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
371                         ls = &accesslog_sc;
372                 else
373                         ls = &changelog_sc;
374                 lattrs[0] = ls->ls_dn.bv_val;
375                 lattrs[1] = ls->ls_req.bv_val;
376                 lattrs[2] = ls->ls_mod.bv_val;
377                 lattrs[3] = ls->ls_newRdn.bv_val;
378                 lattrs[4] = ls->ls_delRdn.bv_val;
379                 lattrs[5] = ls->ls_newSup.bv_val;
380                 lattrs[6] = slap_schema.si_ad_entryCSN->ad_cname.bv_val;
381                 lattrs[7] = NULL;
382
383                 rhint = 0;
384                 base = si->si_logbase.bv_val;
385                 filter = si->si_logfilterstr.bv_val;
386                 attrs = lattrs;
387                 attrsonly = 0;
388                 scope = LDAP_SCOPE_SUBTREE;
389         } else {
390                 rhint = 1;
391                 base = si->si_base.bv_val;
392                 filter = si->si_filterstr.bv_val;
393                 attrs = si->si_attrs;
394                 attrsonly = si->si_attrsonly;
395                 scope = si->si_scope;
396         }
397         if ( si->si_syncdata && si->si_logstate == SYNCLOG_FALLBACK ) {
398                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
399         } else {
400                 si->si_type = si->si_ctype;
401         }
402
403         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
404         {
405                 ber_printf( ber, "{eOb}",
406                         abs(si->si_type), &si->si_syncCookie.octet_str, rhint );
407         } else {
408                 ber_printf( ber, "{eb}",
409                         abs(si->si_type), rhint );
410         }
411
412         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 ) ) == -1 ) {
413                 ber_free_buf( ber );
414                 return rc;
415         }
416
417         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
418         c[0].ldctl_iscritical = si->si_type < 0;
419         ctrls[0] = &c[0];
420
421         c[1].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
422         BER_BVZERO( &c[1].ldctl_value );
423         c[1].ldctl_iscritical = 1;
424         ctrls[1] = &c[1];
425
426         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
427                 c[2].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
428                 c[2].ldctl_value = si->si_bindconf.sb_authzId;
429                 c[2].ldctl_iscritical = 1;
430                 ctrls[2] = &c[2];
431                 ctrls[3] = NULL;
432         } else {
433                 ctrls[2] = NULL;
434         }
435
436         rc = ldap_search_ext( si->si_ld, base, scope, filter, attrs, attrsonly,
437                 ctrls, NULL, NULL, si->si_slimit, &si->si_msgid );
438         ber_free_buf( ber );
439         return rc;
440 }
441
442 static int
443 check_syncprov(
444         Operation *op,
445         syncinfo_t *si )
446 {
447         AttributeName at[2];
448         Attribute a = {0};
449         Entry e = {0};
450         SlapReply rs = {0};
451         int i, j, changed = 0;
452
453         /* Look for contextCSN from syncprov overlay. If
454          * there's no overlay, this will be a no-op. That means
455          * this is a pure consumer, so local changes will not be
456          * allowed, and all changes will already be reflected in
457          * the cookieState.
458          */
459         a.a_desc = slap_schema.si_ad_contextCSN;
460         e.e_attrs = &a;
461         e.e_name = op->o_bd->be_suffix[0];
462         e.e_nname = op->o_bd->be_nsuffix[0];
463         at[0].an_name = a.a_desc->ad_cname;
464         at[0].an_desc = a.a_desc;
465         BER_BVZERO( &at[1].an_name );
466         rs.sr_entry = &e;
467         rs.sr_flags = REP_ENTRY_MODIFIABLE;
468         rs.sr_attrs = at;
469         op->o_req_dn = e.e_name;
470         op->o_req_ndn = e.e_nname;
471
472         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
473         i = backend_operational( op, &rs );
474         if ( i == LDAP_SUCCESS && a.a_nvals ) {
475                 int num = a.a_numvals;
476                 /* check for differences */
477                 if ( num != si->si_cookieState->cs_num ) {
478                         changed = 1;
479                 } else {
480                         for ( i=0; i<num; i++ ) {
481                                 if ( ber_bvcmp( &a.a_nvals[i],
482                                         &si->si_cookieState->cs_vals[i] )) {
483                                         changed = 1;
484                                         break;
485                                 }
486                         }
487                 }
488                 if ( changed ) {
489                         ber_bvarray_free( si->si_cookieState->cs_vals );
490                         ch_free( si->si_cookieState->cs_sids );
491                         si->si_cookieState->cs_num = num;
492                         si->si_cookieState->cs_vals = a.a_nvals;
493                         si->si_cookieState->cs_sids = slap_parse_csn_sids( a.a_nvals,
494                                 num, NULL );
495                         si->si_cookieState->cs_age++;
496                 } else {
497                         ber_bvarray_free( a.a_nvals );
498                 }
499                 ber_bvarray_free( a.a_vals );
500         }
501         /* See if the cookieState has changed due to anything outside
502          * this particular consumer. That includes other consumers in
503          * the same context, or local changes detected above.
504          */
505         if ( si->si_cookieState->cs_num > 0 && si->si_cookieAge !=
506                 si->si_cookieState->cs_age ) {
507                 if ( !si->si_syncCookie.numcsns ) {
508                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
509                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
510                                 si->si_cookieState->cs_vals, NULL );
511                         changed = 1;
512                 } else {
513                         for (i=0; !BER_BVISNULL( &si->si_syncCookie.ctxcsn[i] ); i++) {
514                                 /* bogus, just dup everything */
515                                 if ( si->si_syncCookie.sids[i] == -1 ) {
516                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
517                                         ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
518                                                 si->si_cookieState->cs_vals, NULL );
519                                         changed = 1;
520                                         break;
521                                 }
522                                 for (j=0; j<si->si_cookieState->cs_num; j++) {
523                                         if ( si->si_syncCookie.sids[i] !=
524                                                 si->si_cookieState->cs_sids[j] )
525                                                 continue;
526                                         if ( bvmatch( &si->si_syncCookie.ctxcsn[i],
527                                                 &si->si_cookieState->cs_vals[j] ))
528                                                 break;
529                                         ber_bvreplace( &si->si_syncCookie.ctxcsn[i],
530                                                 &si->si_cookieState->cs_vals[j] );
531                                         changed = 1;
532                                         break;
533                                 }
534                         }
535                 }
536         }
537         if ( changed ) {
538                 si->si_cookieAge = si->si_cookieState->cs_age;
539                 ch_free( si->si_syncCookie.octet_str.bv_val );
540                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
541                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
542                         si->si_syncCookie.sid );
543         }
544         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
545         return changed;
546 }
547
548 static int
549 do_syncrep1(
550         Operation *op,
551         syncinfo_t *si )
552 {
553         int     rc;
554         int cmdline_cookie_found = 0;
555
556         struct sync_cookie      *sc = NULL;
557 #ifdef HAVE_TLS
558         void    *ssl;
559 #endif
560
561         rc = slap_client_connect( &si->si_ld, &si->si_bindconf );
562         if ( rc != LDAP_SUCCESS ) {
563                 goto done;
564         }
565         op->o_protocol = LDAP_VERSION3;
566
567         /* Set SSF to strongest of TLS, SASL SSFs */
568         op->o_sasl_ssf = 0;
569         op->o_tls_ssf = 0;
570         op->o_transport_ssf = 0;
571 #ifdef HAVE_TLS
572         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
573                 == LDAP_SUCCESS && ssl != NULL )
574         {
575                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
576         }
577 #endif /* HAVE_TLS */
578         {
579                 ber_len_t ssf; /* ITS#5403, 3864 LDAP_OPT_X_SASL_SSF probably ought
580                                                   to use sasl_ssf_t but currently uses ber_len_t */
581                 ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &ssf );
582                 op->o_sasl_ssf = ssf;
583         }
584         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
585                 ?  op->o_sasl_ssf : op->o_tls_ssf;
586
587         ldap_set_option( si->si_ld, LDAP_OPT_TIMELIMIT, &si->si_tlimit );
588
589         rc = LDAP_DEREF_NEVER;  /* actually could allow DEREF_FINDING */
590         ldap_set_option( si->si_ld, LDAP_OPT_DEREF, &rc );
591
592         ldap_set_option( si->si_ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF );
593
594         si->si_syncCookie.rid = si->si_rid;
595
596         /* whenever there are multiple data sources possible, advertise sid */
597         si->si_syncCookie.sid = ( SLAP_MULTIMASTER( si->si_be ) || si->si_be != si->si_wbe ) ?
598                 slap_serverID : -1;
599
600         /* We've just started up, or the remote server hasn't sent us
601          * any meaningful state.
602          */
603         if ( BER_BVISNULL( &si->si_syncCookie.octet_str ) ) {
604                 int i;
605
606                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
607                         if ( si->si_rid == sc->rid ) {
608                                 cmdline_cookie_found = 1;
609                                 break;
610                         }
611                 }
612
613                 if ( cmdline_cookie_found ) {
614                         /* cookie is supplied in the command line */
615
616                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
617
618                         /* ctxcsn wasn't parsed yet, do it now */
619                         slap_parse_sync_cookie( sc, op->o_tmpmemctx );
620                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
621                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
622                         slap_sync_cookie_free( sc, 1 );
623                 } else {
624                         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
625                         if ( !si->si_cookieState->cs_num ) {
626                                 /* get contextCSN shadow replica from database */
627                                 BerVarray csn = NULL;
628                                 void *ctx = op->o_tmpmemctx;
629
630                                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
631                                 op->o_req_dn = op->o_req_ndn;
632
633                                 /* try to read stored contextCSN */
634                                 op->o_tmpmemctx = NULL;
635                                 backend_attribute( op, NULL, &op->o_req_ndn,
636                                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
637                                 op->o_tmpmemctx = ctx;
638                                 if ( csn ) {
639                                         si->si_cookieState->cs_vals = csn;
640                                         for (i=0; !BER_BVISNULL( &csn[i] ); i++);
641                                         si->si_cookieState->cs_num = i;
642                                         si->si_cookieState->cs_sids = slap_parse_csn_sids( csn, i, NULL );
643                                 }
644                         }
645                         if ( si->si_cookieState->cs_num ) {
646                                 ber_bvarray_free( si->si_syncCookie.ctxcsn );
647                                 if ( ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
648                                         si->si_cookieState->cs_vals, NULL )) {
649                                         rc = LDAP_NO_MEMORY;
650                                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
651                                         goto done;
652                                 }
653                                 si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
654                                 si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num *
655                                         sizeof(int) );
656                                 for ( i=0; i<si->si_syncCookie.numcsns; i++ )
657                                         si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
658                         }
659                         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
660                 }
661
662                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
663                         si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
664                         si->si_syncCookie.sid );
665         } else {
666                 /* Look for contextCSN from syncprov overlay. */
667                 check_syncprov( op, si );
668         }
669
670         si->si_refreshDone = 0;
671
672         rc = ldap_sync_search( si, op->o_tmpmemctx );
673
674         if( rc != LDAP_SUCCESS ) {
675                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s "
676                         "ldap_search_ext: %s (%d)\n",
677                         si->si_ridtxt, ldap_err2string( rc ), rc );
678         }
679
680 done:
681         if ( rc ) {
682                 if ( si->si_ld ) {
683                         ldap_unbind_ext( si->si_ld, NULL, NULL );
684                         si->si_ld = NULL;
685                 }
686         }
687
688         return rc;
689 }
690
691 static int
692 compare_csns( struct sync_cookie *sc1, struct sync_cookie *sc2, int *which )
693 {
694         int i, j, match = 0;
695         const char *text;
696
697         *which = 0;
698
699         if ( sc1->numcsns < sc2->numcsns ) {
700                 *which = sc1->numcsns;
701                 return -1;
702         }
703
704         for (j=0; j<sc2->numcsns; j++) {
705                 for (i=0; i<sc1->numcsns; i++) {
706                         if ( sc1->sids[i] != sc2->sids[j] )
707                                 continue;
708                         value_match( &match, slap_schema.si_ad_entryCSN,
709                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
710                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
711                                 &sc1->ctxcsn[i], &sc2->ctxcsn[j], &text );
712                         if ( match < 0 ) {
713                                 *which = j;
714                                 return match;
715                         }
716                         break;
717                 }
718                 if ( i == sc1->numcsns ) {
719                         /* sc2 has a sid sc1 lacks */
720                         *which = j;
721                         return -1;
722                 }
723         }
724         return match;
725 }
726
727 #define SYNC_PAUSED     -3
728
729 static int
730 do_syncrep2(
731         Operation *op,
732         syncinfo_t *si )
733 {
734         LDAPControl     **rctrls = NULL;
735
736         BerElementBuffer berbuf;
737         BerElement      *ber = (BerElement *)&berbuf;
738
739         LDAPMessage     *msg = NULL;
740
741         char            *retoid = NULL;
742         struct berval   *retdata = NULL;
743
744         Entry           *entry = NULL;
745
746         int             syncstate;
747         struct berval   syncUUID = BER_BVNULL;
748         struct sync_cookie      syncCookie = { NULL };
749         struct sync_cookie      syncCookie_req = { NULL };
750         struct berval           cookie = BER_BVNULL;
751
752         int             rc,
753                         err = LDAP_SUCCESS;
754         ber_len_t       len;
755
756         struct berval   *psub;
757         Modifications   *modlist = NULL;
758
759         int                             match, m;
760
761         struct timeval *tout_p = NULL;
762         struct timeval tout = { 0, 0 };
763
764         int             refreshDeletes = 0;
765         BerVarray syncUUIDs = NULL;
766         ber_tag_t si_tag;
767
768         if ( slapd_shutdown ) {
769                 rc = -2;
770                 goto done;
771         }
772
773         ber_init2( ber, NULL, LBER_USE_DER );
774         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
775
776         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 %s\n", si->si_ridtxt, 0, 0 );
777
778         psub = &si->si_be->be_nsuffix[0];
779
780         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
781
782         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
783                 tout_p = &tout;
784         } else {
785                 tout_p = NULL;
786         }
787
788         while ( ( rc = ldap_result( si->si_ld, si->si_msgid, LDAP_MSG_ONE,
789                 tout_p, &msg ) ) > 0 )
790         {
791                 LDAPControl     *rctrlp = NULL;
792
793                 if ( slapd_shutdown ) {
794                         rc = -2;
795                         goto done;
796                 }
797                 switch( ldap_msgtype( msg ) ) {
798                 case LDAP_RES_SEARCH_ENTRY:
799                         ldap_get_entry_controls( si->si_ld, msg, &rctrls );
800                         /* we can't work without the control */
801                         if ( rctrls ) {
802                                 LDAPControl **next;
803                                 /* NOTE: make sure we use the right one;
804                                  * a better approach would be to run thru
805                                  * the whole list and take care of all */
806                                 /* NOTE: since we issue the search request,
807                                  * we should know what controls to expect,
808                                  * and there should be none apart from the
809                                  * sync-related control */
810                                 rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_STATE, rctrls, &next );
811                                 if ( next && ldap_control_find( LDAP_CONTROL_SYNC_STATE, next, NULL ) )
812                                 {
813                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
814                                                 "got search entry with multiple "
815                                                 "Sync State control\n", si->si_ridtxt, 0, 0 );
816                                         ldap_controls_free( rctrls );
817                                         rc = -1;
818                                         goto done;
819                                 }
820                         }
821                         if ( rctrlp == NULL ) {
822                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
823                                         "got search entry without "
824                                         "Sync State control\n", si->si_ridtxt, 0, 0 );
825                                 rc = -1;
826                                 goto done;
827                         }
828                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
829                         ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
830                         /* FIXME: what if syncUUID is NULL or empty?
831                          * (happens with back-sql...) */
832                         if ( BER_BVISEMPTY( &syncUUID ) ) {
833                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
834                                         "got empty syncUUID with LDAP_SYNC_%s\n",
835                                         si->si_ridtxt,
836                                         syncrepl_state2str( syncstate ), 0 );
837                                 ldap_controls_free( rctrls );
838                                 rc = -1;
839                                 goto done;
840                         }
841                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
842                                 ber_scanf( ber, /*"{"*/ "m}", &cookie );
843
844                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: cookie=%s\n",
845                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0, 0 );
846
847                                 if ( !BER_BVISNULL( &cookie ) ) {
848                                         ch_free( syncCookie.octet_str.bv_val );
849                                         ber_dupbv( &syncCookie.octet_str, &cookie );
850                                 }
851                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
852                                 {
853                                         slap_parse_sync_cookie( &syncCookie, NULL );
854                                         if ( syncCookie.ctxcsn ) {
855                                                 int i, sid = slap_parse_csn_sid( syncCookie.ctxcsn );
856                                                 for ( i =0; i<si->si_cookieState->cs_num; i++ ) {
857                                                         if ( si->si_cookieState->cs_sids[i] == sid && 
858                                                                 ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_vals[i] ) <= 0 ) {
859                                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN too old, ignoring %s\n",
860                                                                         si->si_ridtxt, syncCookie.ctxcsn->bv_val, 0 );
861                                                                 ldap_controls_free( rctrls );
862                                                                 rc = 0;
863                                                                 goto done;
864                                                         }
865                                                 }
866                                         }
867                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
868                                 }
869                         }
870                         rc = 0;
871                         if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
872                                 modlist = NULL;
873                                 if ( ( rc = syncrepl_message_to_op( si, op, msg ) ) == LDAP_SUCCESS &&
874                                         syncCookie.ctxcsn )
875                                 {
876                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
877                                 } else switch ( rc ) {
878                                         case LDAP_ALREADY_EXISTS:
879                                         case LDAP_NO_SUCH_OBJECT:
880                                         case LDAP_NO_SUCH_ATTRIBUTE:
881                                         case LDAP_TYPE_OR_VALUE_EXISTS:
882                                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
883                                                 si->si_logstate = SYNCLOG_FALLBACK;
884                                                 ldap_abandon_ext( si->si_ld, si->si_msgid, NULL, NULL );
885                                                 break;
886                                         default:
887                                                 break;
888                                 }
889                         } else if ( ( rc = syncrepl_message_to_entry( si, op, msg,
890                                 &modlist, &entry, syncstate ) ) == LDAP_SUCCESS )
891                         {
892                                 if ( ( rc = syncrepl_entry( si, op, entry, &modlist,
893                                         syncstate, &syncUUID, syncCookie.ctxcsn ) ) == LDAP_SUCCESS &&
894                                         syncCookie.ctxcsn )
895                                 {
896                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
897                                 }
898                         }
899                         ldap_controls_free( rctrls );
900                         if ( modlist ) {
901                                 slap_mods_free( modlist, 1 );
902                         }
903                         if ( rc )
904                                 goto done;
905                         break;
906
907                 case LDAP_RES_SEARCH_REFERENCE:
908                         Debug( LDAP_DEBUG_ANY,
909                                 "do_syncrep2: %s reference received error\n",
910                                 si->si_ridtxt, 0, 0 );
911                         break;
912
913                 case LDAP_RES_SEARCH_RESULT:
914                         Debug( LDAP_DEBUG_SYNC,
915                                 "do_syncrep2: %s LDAP_RES_SEARCH_RESULT\n",
916                                 si->si_ridtxt, 0, 0 );
917                         ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
918                                 &rctrls, 0 );
919 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
920                         if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
921                                 /* map old result code to registered code */
922                                 err = LDAP_SYNC_REFRESH_REQUIRED;
923                         }
924 #endif
925                         if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
926                                 if ( si->si_logstate == SYNCLOG_LOGGING ) {
927                                         si->si_logstate = SYNCLOG_FALLBACK;
928                                 }
929                                 rc = err;
930                                 goto done;
931                         }
932                         if ( err ) {
933                                 Debug( LDAP_DEBUG_ANY,
934                                         "do_syncrep2: %s LDAP_RES_SEARCH_RESULT (%d) %s\n",
935                                         si->si_ridtxt, err, ldap_err2string( err ) );
936                         }
937                         if ( rctrls ) {
938                                 LDAPControl **next;
939                                 /* NOTE: make sure we use the right one;
940                                  * a better approach would be to run thru
941                                  * the whole list and take care of all */
942                                 /* NOTE: since we issue the search request,
943                                  * we should know what controls to expect,
944                                  * and there should be none apart from the
945                                  * sync-related control */
946                                 rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_DONE, rctrls, &next );
947                                 if ( next && ldap_control_find( LDAP_CONTROL_SYNC_DONE, next, NULL ) )
948                                 {
949                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
950                                                 "got search result with multiple "
951                                                 "Sync State control\n", si->si_ridtxt, 0, 0 );
952                                         ldap_controls_free( rctrls );
953                                         rc = -1;
954                                         goto done;
955                                 }
956                         }
957                         if ( rctrlp ) {
958                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
959
960                                 ber_scanf( ber, "{" /*"}"*/);
961                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
962                                         ber_scanf( ber, "m", &cookie );
963
964                                         Debug( LDAP_DEBUG_SYNC, "do_syncrep2: cookie=%s\n",
965                                                 BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0, 0 );
966
967                                         if ( !BER_BVISNULL( &cookie ) ) {
968                                                 ch_free( syncCookie.octet_str.bv_val );
969                                                 ber_dupbv( &syncCookie.octet_str, &cookie);
970                                         }
971                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
972                                         {
973                                                 slap_parse_sync_cookie( &syncCookie, NULL );
974                                                 op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
975                                         }
976                                 }
977                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
978                                 {
979                                         ber_scanf( ber, "b", &refreshDeletes );
980                                 }
981                                 ber_scanf( ber, /*"{"*/ "}" );
982                         }
983                         if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
984                                 slap_sync_cookie_free( &syncCookie_req, 0 );
985                                 slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
986                         }
987                         if ( !syncCookie.ctxcsn ) {
988                                 match = 1;
989                         } else if ( !syncCookie_req.ctxcsn ) {
990                                 match = -1;
991                                 m = 0;
992                         } else {
993                                 match = compare_csns( &syncCookie_req, &syncCookie, &m );
994                         }
995                         if ( rctrls ) {
996                                 ldap_controls_free( rctrls );
997                         }
998                         if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
999                                 /* FIXME : different error behaviors according to
1000                                  *      1) err code : LDAP_BUSY ...
1001                                  *      2) on err policy : stop service, stop sync, retry
1002                                  */
1003                                 if ( refreshDeletes == 0 && match < 0 &&
1004                                         err == LDAP_SUCCESS &&
1005                                         syncCookie_req.numcsns == syncCookie.numcsns )
1006                                 {
1007                                         syncrepl_del_nonpresent( op, si, NULL,
1008                                                 &syncCookie, m );
1009                                 } else {
1010                                         avl_free( si->si_presentlist, ch_free );
1011                                         si->si_presentlist = NULL;
1012                                 }
1013                         }
1014                         if ( syncCookie.ctxcsn && match < 0 && err == LDAP_SUCCESS )
1015                         {
1016                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
1017                         }
1018                         if ( err == LDAP_SUCCESS
1019                                 && si->si_logstate == SYNCLOG_FALLBACK ) {
1020                                 si->si_logstate = SYNCLOG_LOGGING;
1021                                 rc = LDAP_SYNC_REFRESH_REQUIRED;
1022                         } else {
1023                                 rc = -2;
1024                         }
1025                         goto done;
1026                         break;
1027
1028                 case LDAP_RES_INTERMEDIATE:
1029                         rc = ldap_parse_intermediate( si->si_ld, msg,
1030                                 &retoid, &retdata, NULL, 0 );
1031                         if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
1032                                 ber_init2( ber, retdata, LBER_USE_DER );
1033
1034                                 switch ( si_tag = ber_peek_tag( ber, &len ) ) {
1035                                 ber_tag_t tag;
1036                                 case LDAP_TAG_SYNC_NEW_COOKIE:
1037                                         Debug( LDAP_DEBUG_SYNC,
1038                                                 "do_syncrep2: %s %s - %s\n", 
1039                                                 si->si_ridtxt,
1040                                                 "LDAP_RES_INTERMEDIATE", 
1041                                                 "NEW_COOKIE" );
1042                                         ber_scanf( ber, "tm", &tag, &cookie );
1043                                         Debug( LDAP_DEBUG_SYNC,
1044                                                 "do_syncrep2: %s NEW_COOKIE: %s\n",
1045                                                 si->si_ridtxt,
1046                                                 cookie.bv_val, 0);
1047                                         if ( !BER_BVISNULL( &cookie ) ) {
1048                                                 ch_free( syncCookie.octet_str.bv_val );
1049                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
1050                                         }
1051                                         if (!BER_BVISNULL( &syncCookie.octet_str ) ) {
1052                                                 slap_parse_sync_cookie( &syncCookie, NULL );
1053                                                 op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1054                                         }
1055                                         break;
1056                                 case LDAP_TAG_SYNC_REFRESH_DELETE:
1057                                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
1058                                         Debug( LDAP_DEBUG_SYNC,
1059                                                 "do_syncrep2: %s %s - %s\n", 
1060                                                 si->si_ridtxt,
1061                                                 "LDAP_RES_INTERMEDIATE", 
1062                                                 si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
1063                                                 "REFRESH_PRESENT" : "REFRESH_DELETE" );
1064                                         if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
1065                                                 si->si_refreshDelete = 1;
1066                                         } else {
1067                                                 si->si_refreshPresent = 1;
1068                                         }
1069                                         ber_scanf( ber, "t{" /*"}"*/, &tag );
1070                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
1071                                         {
1072                                                 ber_scanf( ber, "m", &cookie );
1073
1074                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: cookie=%s\n",
1075                                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0, 0 );
1076
1077                                                 if ( !BER_BVISNULL( &cookie ) ) {
1078                                                         ch_free( syncCookie.octet_str.bv_val );
1079                                                         ber_dupbv( &syncCookie.octet_str, &cookie );
1080                                                 }
1081                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1082                                                 {
1083                                                         slap_parse_sync_cookie( &syncCookie, NULL );
1084                                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1085                                                 }
1086                                         }
1087                                         /* Defaults to TRUE */
1088                                         if ( ber_peek_tag( ber, &len ) ==
1089                                                 LDAP_TAG_REFRESHDONE )
1090                                         {
1091                                                 ber_scanf( ber, "b", &si->si_refreshDone );
1092                                         } else
1093                                         {
1094                                                 si->si_refreshDone = 1;
1095                                         }
1096                                         ber_scanf( ber, /*"{"*/ "}" );
1097                                         break;
1098                                 case LDAP_TAG_SYNC_ID_SET:
1099                                         Debug( LDAP_DEBUG_SYNC,
1100                                                 "do_syncrep2: %s %s - %s\n", 
1101                                                 si->si_ridtxt,
1102                                                 "LDAP_RES_INTERMEDIATE", 
1103                                                 "SYNC_ID_SET" );
1104                                         ber_scanf( ber, "t{" /*"}"*/, &tag );
1105                                         if ( ber_peek_tag( ber, &len ) ==
1106                                                 LDAP_TAG_SYNC_COOKIE )
1107                                         {
1108                                                 ber_scanf( ber, "m", &cookie );
1109
1110                                                 Debug( LDAP_DEBUG_SYNC, "do_syncrep2: cookie=%s\n",
1111                                                         BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0, 0 );
1112
1113                                                 if ( !BER_BVISNULL( &cookie ) ) {
1114                                                         ch_free( syncCookie.octet_str.bv_val );
1115                                                         ber_dupbv( &syncCookie.octet_str, &cookie );
1116                                                 }
1117                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1118                                                 {
1119                                                         slap_parse_sync_cookie( &syncCookie, NULL );
1120                                                         op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1121                                                         compare_csns( &syncCookie_req, &syncCookie, &m );
1122                                                 }
1123                                         }
1124                                         if ( ber_peek_tag( ber, &len ) ==
1125                                                 LDAP_TAG_REFRESHDELETES )
1126                                         {
1127                                                 ber_scanf( ber, "b", &refreshDeletes );
1128                                         }
1129                                         ber_scanf( ber, "[W]", &syncUUIDs );
1130                                         ber_scanf( ber, /*"{"*/ "}" );
1131                                         if ( refreshDeletes ) {
1132                                                 syncrepl_del_nonpresent( op, si, syncUUIDs,
1133                                                         &syncCookie, m );
1134                                                 ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
1135                                         } else {
1136                                                 int i;
1137                                                 for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
1138                                                         (void)avl_presentlist_insert( si, &syncUUIDs[i] );
1139                                                         slap_sl_free( syncUUIDs[i].bv_val, op->o_tmpmemctx );
1140                                                 }
1141                                                 slap_sl_free( syncUUIDs, op->o_tmpmemctx );
1142                                         }
1143                                         slap_sync_cookie_free( &syncCookie, 0 );
1144                                         break;
1145                                 default:
1146                                         Debug( LDAP_DEBUG_ANY,
1147                                                 "do_syncrep2: %s unknown syncinfo tag (%ld)\n",
1148                                                 si->si_ridtxt, (long) si_tag, 0 );
1149                                         ldap_memfree( retoid );
1150                                         ber_bvfree( retdata );
1151                                         continue;
1152                                 }
1153
1154                                 if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1155                                         slap_sync_cookie_free( &syncCookie_req, 0 );
1156                                         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1157                                 }
1158                                 if ( !syncCookie.ctxcsn ) {
1159                                         match = 1;
1160                                 } else if ( !syncCookie_req.ctxcsn ) {
1161                                         match = -1;
1162                                         m = 0;
1163                                 } else {
1164                                         match = compare_csns( &syncCookie_req, &syncCookie, &m );
1165                                 }
1166
1167                                 if ( match < 0 ) {
1168                                         if ( si->si_refreshPresent == 1 &&
1169                                                 si_tag != LDAP_TAG_SYNC_NEW_COOKIE &&
1170                                                 syncCookie_req.numcsns == syncCookie.numcsns ) {
1171                                                 syncrepl_del_nonpresent( op, si, NULL,
1172                                                         &syncCookie, m );
1173                                         }
1174
1175                                         if ( syncCookie.ctxcsn )
1176                                         {
1177                                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie);
1178                                         }
1179                                 } 
1180
1181                                 ldap_memfree( retoid );
1182                                 ber_bvfree( retdata );
1183                                 break;
1184
1185                         } else {
1186                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1187                                         "unknown intermediate response (%d)\n",
1188                                         si->si_ridtxt, rc, 0 );
1189                                 ldap_memfree( retoid );
1190                                 ber_bvfree( retdata );
1191                                 break;
1192                         }
1193                         break;
1194
1195                 default:
1196                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1197                                 "unknown message (0x%02lx)\n",
1198                                 si->si_ridtxt,
1199                                 (unsigned long)ldap_msgtype( msg ), 0 );
1200                         break;
1201
1202                 }
1203                 if ( !BER_BVISNULL( &syncCookie.octet_str ) ) {
1204                         slap_sync_cookie_free( &syncCookie_req, 0 );
1205                         slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
1206                         slap_sync_cookie_free( &syncCookie, 0 );
1207                 }
1208                 ldap_msgfree( msg );
1209                 msg = NULL;
1210                 if ( ldap_pvt_thread_pool_pausing( &connection_pool )) {
1211                         slap_sync_cookie_free( &syncCookie, 0 );
1212                         slap_sync_cookie_free( &syncCookie_req, 0 );
1213                         return SYNC_PAUSED;
1214                 }
1215         }
1216
1217         if ( rc == -1 ) {
1218                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1219                 err = rc;
1220         }
1221
1222 done:
1223         if ( err != LDAP_SUCCESS ) {
1224                 Debug( LDAP_DEBUG_ANY,
1225                         "do_syncrep2: %s (%d) %s\n",
1226                         si->si_ridtxt, err, ldap_err2string( err ) );
1227         }
1228
1229         slap_sync_cookie_free( &syncCookie, 0 );
1230         slap_sync_cookie_free( &syncCookie_req, 0 );
1231
1232         if ( msg ) ldap_msgfree( msg );
1233
1234         if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
1235                 if ( si->si_conn ) {
1236                         connection_client_stop( si->si_conn );
1237                         si->si_conn = NULL;
1238                 }
1239                 ldap_unbind_ext( si->si_ld, NULL, NULL );
1240                 si->si_ld = NULL;
1241         }
1242
1243         return rc;
1244 }
1245
1246 static void *
1247 do_syncrepl(
1248         void    *ctx,
1249         void    *arg )
1250 {
1251         struct re_s* rtask = arg;
1252         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1253         Connection conn = {0};
1254         OperationBuffer opbuf;
1255         Operation *op;
1256         int rc = LDAP_SUCCESS;
1257         int dostop = 0;
1258         ber_socket_t s;
1259         int i, defer = 1, fail = 0;
1260         Backend *be;
1261
1262         if ( si == NULL )
1263                 return NULL;
1264         if ( slapd_shutdown )
1265                 return NULL;
1266
1267         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl %s\n", si->si_ridtxt, 0, 0 );
1268
1269         /* Don't get stuck here while a pause is initiated */
1270         while ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
1271                 if ( slapd_shutdown )
1272                         return NULL;
1273                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1274                         ldap_pvt_thread_yield();
1275         }
1276
1277         if ( !si->si_ctype )
1278                 goto deleted;
1279
1280         switch( abs( si->si_type ) ) {
1281         case LDAP_SYNC_REFRESH_ONLY:
1282         case LDAP_SYNC_REFRESH_AND_PERSIST:
1283                 break;
1284         default:
1285                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1286                 return NULL;
1287         }
1288
1289         if ( slapd_shutdown ) {
1290                 if ( si->si_ld ) {
1291                         if ( si->si_conn ) {
1292                                 connection_client_stop( si->si_conn );
1293                                 si->si_conn = NULL;
1294                         }
1295                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1296                         si->si_ld = NULL;
1297                 }
1298                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1299                 return NULL;
1300         }
1301
1302         connection_fake_init( &conn, &opbuf, ctx );
1303         op = &opbuf.ob_op;
1304
1305         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1306         be = si->si_be;
1307
1308         /* Coordinate contextCSN updates with any syncprov overlays
1309          * in use. This may be complicated by the use of the glue
1310          * overlay.
1311          *
1312          * Typically there is a single syncprov mastering the entire
1313          * glued tree. In that case, our contextCSN updates should
1314          * go to the master DB. But if there is no syncprov on the
1315          * master DB, then nothing special is needed here.
1316          *
1317          * Alternatively, there may be individual syncprov overlays
1318          * on each glued branch. In that case, each syncprov only
1319          * knows about changes within its own branch. And so our
1320          * contextCSN updates should only go to the local DB.
1321          */
1322         if ( !si->si_wbe ) {
1323                 if ( SLAP_GLUE_SUBORDINATE( be ) && !overlay_is_inst( be, "syncprov" )) {
1324                         BackendDB * top_be = select_backend( &be->be_nsuffix[0], 1 );
1325                         if ( overlay_is_inst( top_be, "syncprov" ))
1326                                 si->si_wbe = select_backend( &be->be_nsuffix[0], 1 );
1327                         else
1328                                 si->si_wbe = be;
1329                 } else {
1330                         si->si_wbe = be;
1331                 }
1332         }
1333         if ( !si->si_schemachecking )
1334                 op->o_no_schema_check = 1;
1335
1336         /* Establish session, do search */
1337         if ( !si->si_ld ) {
1338                 si->si_refreshDelete = 0;
1339                 si->si_refreshPresent = 0;
1340
1341                 /* use main DB when retrieving contextCSN */
1342                 op->o_bd = si->si_wbe;
1343                 op->o_dn = op->o_bd->be_rootdn;
1344                 op->o_ndn = op->o_bd->be_rootndn;
1345                 rc = do_syncrep1( op, si );
1346         }
1347
1348 reload:
1349         /* Process results */
1350         if ( rc == LDAP_SUCCESS ) {
1351                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1352
1353                 /* use current DB */
1354                 op->o_bd = be;
1355                 op->o_dn = op->o_bd->be_rootdn;
1356                 op->o_ndn = op->o_bd->be_rootndn;
1357                 rc = do_syncrep2( op, si );
1358                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1359                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1360                         goto reload;
1361                 }
1362
1363 deleted:
1364                 /* We got deleted while running on cn=config */
1365                 if ( !si->si_ctype ) {
1366                         if ( si->si_conn )
1367                                 dostop = 1;
1368                         rc = -1;
1369                 }
1370
1371                 if ( rc != SYNC_PAUSED ) {
1372                         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1373                                 /* If we succeeded, enable the connection for further listening.
1374                                  * If we failed, tear down the connection and reschedule.
1375                                  */
1376                                 if ( rc == LDAP_SUCCESS ) {
1377                                         if ( si->si_conn ) {
1378                                                 connection_client_enable( si->si_conn );
1379                                         } else {
1380                                                 si->si_conn = connection_client_setup( s, do_syncrepl, arg );
1381                                         } 
1382                                 } else if ( si->si_conn ) {
1383                                         dostop = 1;
1384                                 }
1385                         } else {
1386                                 if ( rc == -2 ) rc = 0;
1387                         }
1388                 }
1389         }
1390
1391         /* At this point, we have 5 cases:
1392          * 1) for any hard failure, give up and remove this task
1393          * 2) for ServerDown, reschedule this task to run later
1394          * 3) for threadpool pause, reschedule to run immediately
1395          * 4) for Refresh and Success, reschedule to run
1396          * 5) for Persist and Success, reschedule to defer
1397          */
1398         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1399
1400         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask ) ) {
1401                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1402         }
1403
1404         if ( dostop ) {
1405                 connection_client_stop( si->si_conn );
1406                 si->si_conn = NULL;
1407         }
1408
1409         if ( rc == SYNC_PAUSED ) {
1410                 rtask->interval.tv_sec = 0;
1411                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1412                 rtask->interval.tv_sec = si->si_interval;
1413                 rc = 0;
1414         } else if ( rc == LDAP_SUCCESS ) {
1415                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1416                         defer = 0;
1417                 }
1418                 rtask->interval.tv_sec = si->si_interval;
1419                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1420                 if ( si->si_retrynum ) {
1421                         for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1422                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1423                         }
1424                         si->si_retrynum[i] = RETRYNUM_TAIL;
1425                 }
1426         } else {
1427                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1428                         if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1429                                 break;
1430                 }
1431
1432                 if ( !si->si_ctype
1433                         || !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1434                         if ( si->si_re ) {
1435                                 ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1436                                 si->si_re = NULL;
1437                         }
1438                         fail = RETRYNUM_TAIL;
1439                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1440                         if ( si->si_retrynum[i] > 0 )
1441                                 si->si_retrynum[i]--;
1442                         fail = si->si_retrynum[i];
1443                         rtask->interval.tv_sec = si->si_retryinterval[i];
1444                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1445                         slap_wake_listener();
1446                 }
1447         }
1448
1449         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1450         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1451
1452         if ( rc ) {
1453                 if ( fail == RETRYNUM_TAIL ) {
1454                         Debug( LDAP_DEBUG_ANY,
1455                                 "do_syncrepl: %s rc %d quitting\n",
1456                                 si->si_ridtxt, rc, 0 );
1457                 } else if ( fail > 0 ) {
1458                         Debug( LDAP_DEBUG_ANY,
1459                                 "do_syncrepl: %s rc %d retrying (%d retries left)\n",
1460                                 si->si_ridtxt, rc, fail );
1461                 } else {
1462                         Debug( LDAP_DEBUG_ANY,
1463                                 "do_syncrepl: %s rc %d retrying\n",
1464                                 si->si_ridtxt, rc, 0 );
1465                 }
1466         }
1467
1468         /* Do final delete cleanup */
1469         if ( !si->si_ctype ) {
1470                 syncinfo_free( si, 0 );
1471         }
1472         return NULL;
1473 }
1474
1475 static slap_verbmasks modops[] = {
1476         { BER_BVC("add"), LDAP_REQ_ADD },
1477         { BER_BVC("delete"), LDAP_REQ_DELETE },
1478         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1479         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1480         { BER_BVNULL, 0 }
1481 };
1482
1483 static Modifications *
1484 syncrepl_accesslog_mods(
1485         syncinfo_t *si,
1486         struct berval *vals
1487 )
1488 {
1489         char *colon;
1490         const char *text;
1491         AttributeDescription *ad;
1492         struct berval bv, bv2;
1493         short op;
1494         Modifications *mod = NULL, *modlist = NULL, **modtail;
1495         int i;
1496
1497         modtail = &modlist;
1498
1499         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1500                 ad = NULL;
1501                 bv = vals[i];
1502
1503                 colon = ber_bvchr( &bv, ':' );
1504                 if ( !colon ) {
1505                         /* Invalid */
1506                         continue;
1507                 }
1508
1509                 bv.bv_len = colon - bv.bv_val;
1510                 if ( slap_bv2ad( &bv, &ad, &text ) ) {
1511                         /* Invalid */
1512                         continue;
1513                 }
1514
1515                 /* Ignore dynamically generated attrs */
1516                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1517                         continue;
1518                 }
1519
1520                 /* Ignore excluded attrs */
1521                 if ( ldap_charray_inlist( si->si_exattrs,
1522                         ad->ad_type->sat_cname.bv_val ) )
1523                 {
1524                         continue;
1525                 }
1526
1527                 switch(colon[1]) {
1528                 case '+':       op = LDAP_MOD_ADD; break;
1529                 case '-':       op = LDAP_MOD_DELETE; break;
1530                 case '=':       op = LDAP_MOD_REPLACE; break;
1531                 case '#':       op = LDAP_MOD_INCREMENT; break;
1532                 default:        continue;
1533                 }
1534
1535                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1536                         mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1537                         mod->sml_flags = 0;
1538                         mod->sml_op = op;
1539                         mod->sml_next = NULL;
1540                         mod->sml_desc = ad;
1541                         mod->sml_type = ad->ad_cname;
1542                         mod->sml_values = NULL;
1543                         mod->sml_nvalues = NULL;
1544                         mod->sml_numvals = 0;
1545
1546                         *modtail = mod;
1547                         modtail = &mod->sml_next;
1548                 }
1549                 if ( colon[2] == ' ' ) {
1550                         bv.bv_val = colon + 3;
1551                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1552                         ber_dupbv( &bv2, &bv );
1553                         ber_bvarray_add( &mod->sml_values, &bv2 );
1554                         mod->sml_numvals++;
1555                 }
1556         }
1557         return modlist;
1558 }
1559
1560 static Modifications *
1561 syncrepl_changelog_mods(
1562         syncinfo_t *si,
1563         struct berval *vals
1564 )
1565 {
1566         return NULL;    /* FIXME */
1567 }
1568
1569 static int
1570 syncrepl_message_to_op(
1571         syncinfo_t      *si,
1572         Operation       *op,
1573         LDAPMessage     *msg
1574 )
1575 {
1576         BerElement      *ber = NULL;
1577         Modifications   *modlist = NULL;
1578         logschema *ls;
1579         SlapReply rs = { REP_RESULT };
1580         slap_callback cb = { NULL, null_callback, NULL, NULL };
1581
1582         const char      *text;
1583         char txtbuf[SLAP_TEXT_BUFLEN];
1584         size_t textlen = sizeof txtbuf;
1585
1586         struct berval   bdn, dn = BER_BVNULL, ndn;
1587         struct berval   bv, *bvals = NULL;
1588         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1589                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1590                 psup = BER_BVNULL, nsup = BER_BVNULL;
1591         int             rc, deleteOldRdn = 0, freeReqDn = 0;
1592         int             do_graduate = 0;
1593
1594         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1595                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1596                         "Message type should be entry (%d)",
1597                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1598                 return -1;
1599         }
1600
1601         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1602                 ls = &accesslog_sc;
1603         else
1604                 ls = &changelog_sc;
1605
1606         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1607
1608         if ( rc != LDAP_SUCCESS ) {
1609                 Debug( LDAP_DEBUG_ANY,
1610                         "syncrepl_message_to_op: %s dn get failed (%d)",
1611                         si->si_ridtxt, rc, 0 );
1612                 return rc;
1613         }
1614
1615         op->o_tag = LBER_DEFAULT;
1616         op->o_bd = si->si_wbe;
1617
1618         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
1619                 == LDAP_SUCCESS ) {
1620                 if ( bv.bv_val == NULL )
1621                         break;
1622
1623                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
1624                         bdn = bvals[0];
1625                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1626                         ber_dupbv( &op->o_req_dn, &dn );
1627                         ber_dupbv( &op->o_req_ndn, &ndn );
1628                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1629                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1630                         freeReqDn = 1;
1631                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
1632                         int i = verb_to_mask( bvals[0].bv_val, modops );
1633                         if ( i < 0 ) {
1634                                 Debug( LDAP_DEBUG_ANY,
1635                                         "syncrepl_message_to_op: %s unknown op %s",
1636                                         si->si_ridtxt, bvals[0].bv_val, 0 );
1637                                 ch_free( bvals );
1638                                 rc = -1;
1639                                 goto done;
1640                         }
1641                         op->o_tag = modops[i].mask;
1642                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
1643                         /* Parse attribute into modlist */
1644                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
1645                                 modlist = syncrepl_accesslog_mods( si, bvals );
1646                         } else {
1647                                 modlist = syncrepl_changelog_mods( si, bvals );
1648                         }
1649                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
1650                         rdn = bvals[0];
1651                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
1652                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
1653                                 deleteOldRdn = 1;
1654                         }
1655                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
1656                         sup = bvals[0];
1657                 } else if ( !ber_bvstrcasecmp( &bv,
1658                         &slap_schema.si_ad_entryCSN->ad_cname ) )
1659                 {
1660                         slap_queue_csn( op, bvals );
1661                         do_graduate = 1;
1662                 }
1663                 ch_free( bvals );
1664         }
1665
1666         /* If we didn't get a mod type or a target DN, bail out */
1667         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
1668                 rc = -1;
1669                 goto done;
1670         }
1671
1672         op->o_callback = &cb;
1673         slap_op_time( &op->o_time, &op->o_tincr );
1674
1675         switch( op->o_tag ) {
1676         case LDAP_REQ_ADD:
1677         case LDAP_REQ_MODIFY:
1678                 /* If we didn't get required data, bail */
1679                 if ( !modlist ) goto done;
1680
1681                 rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
1682
1683                 if ( rc != LDAP_SUCCESS ) {
1684                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1685                                 "mods check (%s)\n",
1686                                 si->si_ridtxt, text, 0 );
1687                         goto done;
1688                 }
1689
1690                 if ( op->o_tag == LDAP_REQ_ADD ) {
1691                         Entry *e = entry_alloc();
1692                         op->ora_e = e;
1693                         op->ora_e->e_name = op->o_req_dn;
1694                         op->ora_e->e_nname = op->o_req_ndn;
1695                         freeReqDn = 0;
1696                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1697                         if( rc != LDAP_SUCCESS ) {
1698                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1699                                 "mods2entry (%s)\n",
1700                                         si->si_ridtxt, text, 0 );
1701                         } else {
1702                                 rc = op->o_bd->be_add( op, &rs );
1703                                 Debug( LDAP_DEBUG_SYNC,
1704                                         "syncrepl_message_to_op: %s be_add %s (%d)\n", 
1705                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1706                                 do_graduate = 0;
1707                         }
1708                         if ( e == op->ora_e )
1709                                 be_entry_release_w( op, op->ora_e );
1710                 } else {
1711                         op->orm_modlist = modlist;
1712                         op->o_bd = si->si_wbe;
1713                         rc = op->o_bd->be_modify( op, &rs );
1714                         modlist = op->orm_modlist;
1715                         Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1716                                 "syncrepl_message_to_op: %s be_modify %s (%d)\n", 
1717                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
1718                         op->o_bd = si->si_be;
1719                         do_graduate = 0;
1720                 }
1721                 break;
1722         case LDAP_REQ_MODRDN:
1723                 if ( BER_BVISNULL( &rdn ) ) goto done;
1724
1725                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
1726                         goto done;
1727                 }
1728                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
1729                         goto done;
1730                 }
1731                 if ( !BER_BVISNULL( &sup ) ) {
1732                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ) ) {
1733                                 goto done;
1734                         }
1735                         op->orr_newSup = &psup;
1736                         op->orr_nnewSup = &nsup;
1737                 } else {
1738                         op->orr_newSup = NULL;
1739                         op->orr_nnewSup = NULL;
1740                 }
1741                 op->orr_newrdn = prdn;
1742                 op->orr_nnewrdn = nrdn;
1743                 op->orr_deleteoldrdn = deleteOldRdn;
1744                 op->orr_modlist = NULL;
1745                 if ( slap_modrdn2mods( op, &rs ) ) {
1746                         goto done;
1747                 }
1748
1749                 /* Append modlist for operational attrs */
1750                 {
1751                         Modifications *m;
1752
1753                         for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
1754                                 ;
1755                         m->sml_next = modlist;
1756                         modlist = NULL;
1757                 }
1758                 rc = op->o_bd->be_modrdn( op, &rs );
1759                 slap_mods_free( op->orr_modlist, 1 );
1760                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1761                         "syncrepl_message_to_op: %s be_modrdn %s (%d)\n", 
1762                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1763                 do_graduate = 0;
1764                 break;
1765         case LDAP_REQ_DELETE:
1766                 rc = op->o_bd->be_delete( op, &rs );
1767                 Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1768                         "syncrepl_message_to_op: %s be_delete %s (%d)\n", 
1769                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
1770                 do_graduate = 0;
1771                 break;
1772         }
1773 done:
1774         if ( do_graduate )
1775                 slap_graduate_commit_csn( op );
1776         op->o_bd = si->si_be;
1777         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
1778         BER_BVZERO( &op->o_csn );
1779         if ( modlist ) {
1780                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1781         }
1782         if ( !BER_BVISNULL( &rdn ) ) {
1783                 if ( !BER_BVISNULL( &nsup ) ) {
1784                         ch_free( nsup.bv_val );
1785                 }
1786                 if ( !BER_BVISNULL( &psup ) ) {
1787                         ch_free( psup.bv_val );
1788                 }
1789                 if ( !BER_BVISNULL( &nrdn ) ) {
1790                         ch_free( nrdn.bv_val );
1791                 }
1792                 if ( !BER_BVISNULL( &prdn ) ) {
1793                         ch_free( prdn.bv_val );
1794                 }
1795         }
1796         if ( freeReqDn ) {
1797                 ch_free( op->o_req_ndn.bv_val );
1798                 ch_free( op->o_req_dn.bv_val );
1799         }
1800         ber_free( ber, 0 );
1801         return rc;
1802 }
1803
1804 static int
1805 syncrepl_message_to_entry(
1806         syncinfo_t      *si,
1807         Operation       *op,
1808         LDAPMessage     *msg,
1809         Modifications   **modlist,
1810         Entry                   **entry,
1811         int             syncstate
1812 )
1813 {
1814         Entry           *e = NULL;
1815         BerElement      *ber = NULL;
1816         Modifications   tmp;
1817         Modifications   *mod;
1818         Modifications   **modtail = modlist;
1819
1820         const char      *text;
1821         char txtbuf[SLAP_TEXT_BUFLEN];
1822         size_t textlen = sizeof txtbuf;
1823
1824         struct berval   bdn = BER_BVNULL, dn, ndn;
1825         int             rc, is_ctx;
1826
1827         *modlist = NULL;
1828
1829         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1830                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
1831                         "Message type should be entry (%d)",
1832                         si->si_ridtxt, ldap_msgtype( msg ), 0 );
1833                 return -1;
1834         }
1835
1836         op->o_tag = LDAP_REQ_ADD;
1837
1838         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1839         if ( rc != LDAP_SUCCESS ) {
1840                 Debug( LDAP_DEBUG_ANY,
1841                         "syncrepl_message_to_entry: %s dn get failed (%d)",
1842                         si->si_ridtxt, rc, 0 );
1843                 return rc;
1844         }
1845
1846         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1847                 /* NOTE: this could be done even before decoding the DN,
1848                  * although encoding errors wouldn't be detected */
1849                 rc = LDAP_SUCCESS;
1850                 goto done;
1851         }
1852
1853         if ( entry == NULL ) {
1854                 return -1;
1855         }
1856
1857         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1858         ber_dupbv( &op->o_req_dn, &dn );
1859         ber_dupbv( &op->o_req_ndn, &ndn );
1860         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1861         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1862
1863         is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
1864
1865         e = entry_alloc();
1866         e->e_name = op->o_req_dn;
1867         e->e_nname = op->o_req_ndn;
1868
1869         while ( ber_remaining( ber ) ) {
1870                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1871                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1872                 {
1873                         break;
1874                 }
1875
1876                 /* Drop all updates to the contextCSN of the context entry
1877                  * (ITS#4622, etc.)
1878                  */
1879                 if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
1880                         slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
1881                         ber_bvarray_free( tmp.sml_values );
1882                         continue;
1883                 }
1884
1885                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
1886
1887                 mod->sml_op = LDAP_MOD_REPLACE;
1888                 mod->sml_flags = 0;
1889                 mod->sml_next = NULL;
1890                 mod->sml_desc = NULL;
1891                 mod->sml_type = tmp.sml_type;
1892                 mod->sml_values = tmp.sml_values;
1893                 mod->sml_nvalues = NULL;
1894                 mod->sml_numvals = 0;   /* slap_mods_check will set this */
1895
1896                 *modtail = mod;
1897                 modtail = &mod->sml_next;
1898         }
1899
1900         if ( *modlist == NULL ) {
1901                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
1902                         si->si_ridtxt, 0, 0 );
1903                 rc = -1;
1904                 goto done;
1905         }
1906
1907         rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
1908
1909         if ( rc != LDAP_SUCCESS ) {
1910                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
1911                         si->si_ridtxt, text, 0 );
1912                 goto done;
1913         }
1914
1915         /* Strip out dynamically generated attrs */
1916         for ( modtail = modlist; *modtail ; ) {
1917                 mod = *modtail;
1918                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1919                         *modtail = mod->sml_next;
1920                         slap_mod_free( &mod->sml_mod, 0 );
1921                         ch_free( mod );
1922                 } else {
1923                         modtail = &mod->sml_next;
1924                 }
1925         }
1926
1927         /* Strip out attrs in exattrs list */
1928         for ( modtail = modlist; *modtail ; ) {
1929                 mod = *modtail;
1930                 if ( ldap_charray_inlist( si->si_exattrs,
1931                         mod->sml_desc->ad_type->sat_cname.bv_val ) )
1932                 {
1933                         *modtail = mod->sml_next;
1934                         slap_mod_free( &mod->sml_mod, 0 );
1935                         ch_free( mod );
1936                 } else {
1937                         modtail = &mod->sml_next;
1938                 }
1939         }
1940
1941         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1942         if( rc != LDAP_SUCCESS ) {
1943                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
1944                         si->si_ridtxt, text, 0 );
1945         }
1946
1947 done:
1948         ber_free( ber, 0 );
1949         if ( rc != LDAP_SUCCESS ) {
1950                 if ( e ) {
1951                         entry_free( e );
1952                         e = NULL;
1953                 }
1954         }
1955         if ( entry )
1956                 *entry = e;
1957
1958         return rc;
1959 }
1960
1961 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1962
1963 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1964  * entry if a previous refresh was interrupted before sending us a new
1965  * context state. We try to compare the new entry to the existing entry
1966  * and ignore the new entry if they are the same.
1967  *
1968  * Also, we may get an update where the entryDN has changed, due to
1969  * a ModDn on the provider. We detect this as well, so we can issue
1970  * the corresponding operation locally.
1971  *
1972  * In the case of a modify, we get a list of all the attributes
1973  * in the original entry. Rather than deleting the entry and re-adding it,
1974  * we issue a Modify request that deletes all the attributes and adds all
1975  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1976  * entry.
1977  *
1978  * We otherwise distinguish ModDN from Modify; in the case of
1979  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
1980  * operational attributes from the entry, and do a regular ModDN.
1981  */
1982 typedef struct dninfo {
1983         Entry *new_entry;
1984         struct berval dn;
1985         struct berval ndn;
1986         struct berval nnewSup;
1987         int renamed;    /* Was an existing entry renamed? */
1988         int delOldRDN;  /* Was old RDN deleted? */
1989         Modifications **modlist;        /* the modlist we received */
1990         Modifications *mods;    /* the modlist we compared */
1991         Attribute *oldNattr;    /* old naming attr */
1992         AttributeDescription *oldDesc;  /* for renames */
1993         AttributeDescription *newDesc;  /* for renames */
1994 } dninfo;
1995
1996 /* return 1 if inserted, 0 otherwise */
1997 static int
1998 avl_presentlist_insert(
1999         syncinfo_t* si,
2000         struct berval *syncUUID )
2001 {
2002         struct berval *syncuuid_bv = ch_malloc( sizeof( struct berval ) + syncUUID->bv_len + 1 );
2003
2004         syncuuid_bv->bv_len = syncUUID->bv_len;
2005         syncuuid_bv->bv_val = (char *)&syncuuid_bv[1];
2006         AC_MEMCPY( syncuuid_bv->bv_val, syncUUID->bv_val, syncUUID->bv_len );
2007         syncuuid_bv->bv_val[ syncuuid_bv->bv_len ] = '\0';
2008
2009         if ( avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
2010                 syncuuid_cmp, avl_dup_error ) )
2011         {
2012                 ch_free( syncuuid_bv );
2013                 return 0;
2014         }
2015
2016         return 1;
2017 }
2018
2019 static int
2020 syncrepl_entry(
2021         syncinfo_t* si,
2022         Operation *op,
2023         Entry* entry,
2024         Modifications** modlist,
2025         int syncstate,
2026         struct berval* syncUUID,
2027         struct berval* syncCSN )
2028 {
2029         Backend *be = op->o_bd;
2030         slap_callback   cb = { NULL, NULL, NULL, NULL };
2031         int syncuuid_inserted = 0;
2032         struct berval   syncUUID_strrep = BER_BVNULL;
2033
2034         SlapReply       rs_search = {REP_RESULT};
2035         SlapReply       rs_delete = {REP_RESULT};
2036         SlapReply       rs_add = {REP_RESULT};
2037         SlapReply       rs_modify = {REP_RESULT};
2038         Filter f = {0};
2039         AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2040         int rc = LDAP_SUCCESS;
2041
2042         struct berval pdn = BER_BVNULL;
2043         dninfo dni = {0};
2044         int     retry = 1;
2045         int     freecsn = 1;
2046
2047         Debug( LDAP_DEBUG_SYNC,
2048                 "syncrepl_entry: %s LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_%s)\n",
2049                 si->si_ridtxt, syncrepl_state2str( syncstate ), 0 );
2050
2051         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
2052                 if ( !si->si_refreshPresent && !si->si_refreshDone ) {
2053                         syncuuid_inserted = avl_presentlist_insert( si, syncUUID );
2054                 }
2055         }
2056
2057         if ( syncstate == LDAP_SYNC_PRESENT ) {
2058                 return 0;
2059         } else if ( syncstate != LDAP_SYNC_DELETE ) {
2060                 if ( entry == NULL ) {
2061                         return 0;
2062                 }
2063         }
2064
2065         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
2066         if ( syncstate != LDAP_SYNC_DELETE ) {
2067                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
2068
2069                 if ( a == NULL ) {
2070                         /* add if missing */
2071                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
2072                                 &syncUUID_strrep, syncUUID );
2073
2074                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
2075                         /* replace only if necessary */
2076                         if ( a->a_nvals != a->a_vals ) {
2077                                 ber_memfree( a->a_nvals[0].bv_val );
2078                                 ber_dupbv( &a->a_nvals[0], syncUUID );
2079                         }
2080                         ber_memfree( a->a_vals[0].bv_val );
2081                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
2082                 }
2083         }
2084
2085         f.f_choice = LDAP_FILTER_EQUALITY;
2086         f.f_ava = &ava;
2087         ava.aa_desc = slap_schema.si_ad_entryUUID;
2088         ava.aa_value = *syncUUID;
2089
2090         if ( syncuuid_inserted ) {
2091                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
2092                         si->si_ridtxt, syncUUID_strrep.bv_val, 0 );
2093         }
2094         op->ors_filter = &f;
2095
2096         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
2097         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
2098                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
2099         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
2100         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
2101                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
2102         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
2103         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
2104
2105         op->o_tag = LDAP_REQ_SEARCH;
2106         op->ors_scope = LDAP_SCOPE_SUBTREE;
2107         op->ors_deref = LDAP_DEREF_NEVER;
2108
2109         /* get the entry for this UUID */
2110         op->o_req_dn = si->si_base;
2111         op->o_req_ndn = si->si_base;
2112
2113         op->o_time = slap_get_time();
2114         op->ors_tlimit = SLAP_NO_LIMIT;
2115         op->ors_slimit = 1;
2116         op->ors_limit = NULL;
2117
2118         op->ors_attrs = slap_anlist_all_attributes;
2119         op->ors_attrsonly = 0;
2120
2121         /* set callback function */
2122         op->o_callback = &cb;
2123         cb.sc_response = dn_callback;
2124         cb.sc_private = &dni;
2125         dni.new_entry = entry;
2126         dni.modlist = modlist;
2127
2128         rc = be->be_search( op, &rs_search );
2129         Debug( LDAP_DEBUG_SYNC,
2130                         "syncrepl_entry: %s be_search (%d)\n", 
2131                         si->si_ridtxt, rc, 0 );
2132
2133         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
2134                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2135         }
2136
2137         cb.sc_response = null_callback;
2138         cb.sc_private = si;
2139
2140         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
2141                 Debug( LDAP_DEBUG_SYNC,
2142                                 "syncrepl_entry: %s %s\n",
2143                                 si->si_ridtxt, entry->e_name.bv_val, 0 );
2144         } else {
2145                 Debug( LDAP_DEBUG_SYNC,
2146                                 "syncrepl_entry: %s %s\n",
2147                                 si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
2148         }
2149
2150         assert( BER_BVISNULL( &op->o_csn ) );
2151         if ( syncCSN ) {
2152                 slap_queue_csn( op, syncCSN );
2153         }
2154
2155         slap_op_time( &op->o_time, &op->o_tincr );
2156         switch ( syncstate ) {
2157         case LDAP_SYNC_ADD:
2158         case LDAP_SYNC_MODIFY:
2159                 if ( BER_BVISNULL( &op->o_csn ))
2160                 {
2161
2162                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
2163                         if ( a ) {
2164                                 /* FIXME: op->o_csn is assumed to be
2165                                  * on the thread's slab; this needs
2166                                  * to be cleared ASAP.
2167                                  * What happens if already present?
2168                                  */
2169                                 assert( BER_BVISNULL( &op->o_csn ) );
2170                                 op->o_csn = a->a_vals[0];
2171                                 freecsn = 0;
2172                         }
2173                 }
2174 retry_add:;
2175                 if ( BER_BVISNULL( &dni.dn ) ) {
2176
2177                         op->o_req_dn = entry->e_name;
2178                         op->o_req_ndn = entry->e_nname;
2179                         op->o_tag = LDAP_REQ_ADD;
2180                         op->ora_e = entry;
2181                         op->o_bd = si->si_wbe;
2182
2183                         rc = op->o_bd->be_add( op, &rs_add );
2184                         Debug( LDAP_DEBUG_SYNC,
2185                                         "syncrepl_entry: %s be_add %s (%d)\n", 
2186                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2187                         switch ( rs_add.sr_err ) {
2188                         case LDAP_SUCCESS:
2189                                 if ( op->ora_e == entry ) {
2190                                         be_entry_release_w( op, entry );
2191                                 }
2192                                 entry = NULL;
2193                                 break;
2194
2195                         case LDAP_REFERRAL:
2196                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
2197                          * only if the suffix entry is not present */
2198                         case LDAP_NO_SUCH_OBJECT:
2199                                 rc = syncrepl_add_glue( op, entry );
2200                                 entry = NULL;
2201                                 break;
2202
2203                         /* if an entry was added via syncrepl_add_glue(),
2204                          * it likely has no entryUUID, so the previous
2205                          * be_search() doesn't find it.  In this case,
2206                          * give syncrepl a chance to modify it. Also
2207                          * allow for entries that were recreated with the
2208                          * same DN but a different entryUUID.
2209                          */
2210                         case LDAP_ALREADY_EXISTS:
2211                                 if ( retry ) {
2212                                         Operation       op2 = *op;
2213                                         SlapReply       rs2 = { 0 };
2214                                         slap_callback   cb2 = { 0 };
2215
2216                                         op2.o_bd = be;
2217                                         op2.o_tag = LDAP_REQ_SEARCH;
2218                                         op2.o_req_dn = entry->e_name;
2219                                         op2.o_req_ndn = entry->e_nname;
2220                                         op2.ors_scope = LDAP_SCOPE_BASE;
2221                                         op2.ors_deref = LDAP_DEREF_NEVER;
2222                                         op2.ors_attrs = slap_anlist_all_attributes;
2223                                         op2.ors_attrsonly = 0;
2224                                         op2.ors_limit = NULL;
2225                                         op2.ors_slimit = 1;
2226                                         op2.ors_tlimit = SLAP_NO_LIMIT;
2227
2228                                         f.f_choice = LDAP_FILTER_PRESENT;
2229                                         f.f_desc = slap_schema.si_ad_objectClass;
2230                                         op2.ors_filter = &f;
2231                                         op2.ors_filterstr = generic_filterstr;
2232
2233                                         op2.o_callback = &cb2;
2234                                         cb2.sc_response = dn_callback;
2235                                         cb2.sc_private = &dni;
2236
2237                                         rc = be->be_search( &op2, &rs2 );
2238                                         if ( rc ) goto done;
2239
2240                                         retry = 0;
2241                                         slap_op_time( &op->o_time, &op->o_tincr );
2242                                         goto retry_add;
2243                                 }
2244                                 /* FALLTHRU */
2245
2246                         default:
2247                                 Debug( LDAP_DEBUG_ANY,
2248                                         "syncrepl_entry: %s be_add %s failed (%d)\n",
2249                                         si->si_ridtxt, op->o_req_dn.bv_val, rs_add.sr_err );
2250                                 break;
2251                         }
2252                         syncCSN = NULL;
2253                         op->o_bd = be;
2254                         goto done;
2255                 }
2256                 /* FALLTHRU */
2257                 op->o_req_dn = dni.dn;
2258                 op->o_req_ndn = dni.ndn;
2259                 if ( dni.renamed ) {
2260                         struct berval noldp, newp;
2261                         Modifications *mod, **modtail, **ml, *m2;
2262                         int i, got_replace = 0, just_rename = 0;
2263
2264                         op->o_tag = LDAP_REQ_MODRDN;
2265                         dnRdn( &entry->e_name, &op->orr_newrdn );
2266                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
2267
2268                         if ( !BER_BVISNULL( &dni.nnewSup )) {
2269                                 dnParent( &entry->e_name, &newp );
2270                                 op->orr_newSup = &newp;
2271                                 op->orr_nnewSup = &dni.nnewSup;
2272                         } else {
2273                                 op->orr_newSup = NULL;
2274                                 op->orr_nnewSup = NULL;
2275                         }
2276                         op->orr_deleteoldrdn = dni.delOldRDN;
2277                         op->orr_modlist = NULL;
2278                         if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
2279                                 goto done;
2280                         }
2281
2282                         /* Drop the RDN-related mods from this op, because their
2283                          * equivalents were just setup by slap_modrdn2mods.
2284                          *
2285                          * If delOldRDN is TRUE then we should see a delete modop
2286                          * for oldDesc. We might see a replace instead.
2287                          *  delete with no values: therefore newDesc != oldDesc.
2288                          *   if oldNattr had only one value, then Drop this op.
2289                          *  delete with 1 value: can only be the oldRDN value. Drop op.
2290                          *  delete with N values: Drop oldRDN value, keep remainder.
2291                          *  replace with 1 value: if oldNattr had only one value and
2292                          *     newDesc == oldDesc, Drop this op.
2293                          * Any other cases must be left intact.
2294                          *
2295                          * We should also see an add modop for newDesc. (But not if
2296                          * we got a replace modop due to delOldRDN.) If it has
2297                          * multiple values, we'll have to drop the new RDN value.
2298                          */
2299                         modtail = &op->orr_modlist;
2300                         if ( dni.delOldRDN ) {
2301                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2302                                         if ( (*ml)->sml_desc == dni.oldDesc ) {
2303                                                 mod = *ml;
2304                                                 if ( mod->sml_op == LDAP_MOD_REPLACE &&
2305                                                         dni.oldDesc != dni.newDesc ) {
2306                                                         /* This Replace is due to other Mods.
2307                                                          * Just let it ride.
2308                                                          */
2309                                                         continue;
2310                                                 }
2311                                                 if ( mod->sml_numvals <= 1 &&
2312                                                         dni.oldNattr->a_numvals == 1 &&
2313                                                         ( mod->sml_op == LDAP_MOD_DELETE ||
2314                                                           mod->sml_op == LDAP_MOD_REPLACE )) {
2315                                                         if ( mod->sml_op == LDAP_MOD_REPLACE )
2316                                                                 got_replace = 1;
2317                                                         /* Drop this op */
2318                                                         *ml = mod->sml_next;
2319                                                         mod->sml_next = NULL;
2320                                                         slap_mods_free( mod, 1 );
2321                                                         break;
2322                                                 }
2323                                                 if ( mod->sml_op != LDAP_MOD_DELETE || mod->sml_numvals == 0 )
2324                                                         continue;
2325                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2326                                                         if ( m2->sml_desc == dni.oldDesc &&
2327                                                                 m2->sml_op == LDAP_MOD_DELETE ) break;
2328                                                 }
2329                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
2330                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2331                                                                 mod->sml_numvals--;
2332                                                                 ch_free( mod->sml_values[i].bv_val );
2333                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2334                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2335                                                                 if ( mod->sml_nvalues ) {
2336                                                                         ch_free( mod->sml_nvalues[i].bv_val );
2337                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2338                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2339                                                                 }
2340                                                                 break;
2341                                                         }
2342                                                 }
2343                                                 if ( !mod->sml_numvals ) {
2344                                                         /* Drop this op */
2345                                                         *ml = mod->sml_next;
2346                                                         mod->sml_next = NULL;
2347                                                         slap_mods_free( mod, 1 );
2348                                                 }
2349                                                 break;
2350                                         }
2351                                 }
2352                         }
2353                         if ( !got_replace ) {
2354                                 for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2355                                         if ( (*ml)->sml_desc == dni.newDesc ) {
2356                                                 mod = *ml;
2357                                                 if ( mod->sml_op != LDAP_MOD_ADD )
2358                                                         continue;
2359                                                 if ( mod->sml_numvals == 1 ) {
2360                                                         /* Drop this op */
2361                                                         *ml = mod->sml_next;
2362                                                         mod->sml_next = NULL;
2363                                                         slap_mods_free( mod, 1 );
2364                                                         break;
2365                                                 }
2366                                                 for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2367                                                         if ( m2->sml_desc == dni.oldDesc &&
2368                                                                 m2->sml_op == SLAP_MOD_SOFTADD ) break;
2369                                                 }
2370                                                 for ( i=0; i<mod->sml_numvals; i++ ) {
2371                                                         if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2372                                                                 mod->sml_numvals--;
2373                                                                 ch_free( mod->sml_values[i].bv_val );
2374                                                                 mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2375                                                                 BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2376                                                                 if ( mod->sml_nvalues ) {
2377                                                                         ch_free( mod->sml_nvalues[i].bv_val );
2378                                                                         mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2379                                                                         BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2380                                                                 }
2381                                                                 break;
2382                                                         }
2383                                                 }
2384                                                 break;
2385                                         }
2386                                 }
2387                         }
2388
2389                         /* RDNs must be NUL-terminated for back-ldap */
2390                         noldp = op->orr_newrdn;
2391                         ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
2392                         noldp = op->orr_nnewrdn;
2393                         ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
2394
2395                         /* Setup opattrs too */
2396                         {
2397                                 static AttributeDescription *nullattr = NULL;
2398                                 static AttributeDescription **const opattrs[] = {
2399                                         &slap_schema.si_ad_entryCSN,
2400                                         &slap_schema.si_ad_modifiersName,
2401                                         &slap_schema.si_ad_modifyTimestamp,
2402                                         &nullattr
2403                                 };
2404                                 AttributeDescription *opattr;
2405                                 int i;
2406
2407                                 modtail = &m2;
2408                                 /* pull mod off incoming modlist */
2409                                 for ( i = 0; (opattr = *opattrs[i]) != NULL; i++ ) {
2410                                         for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next )
2411                                         {
2412                                                 if ( (*ml)->sml_desc == opattr ) {
2413                                                         mod = *ml;
2414                                                         *ml = mod->sml_next;
2415                                                         mod->sml_next = NULL;
2416                                                         *modtail = mod;
2417                                                         modtail = &mod->sml_next;
2418                                                         break;
2419                                                 }
2420                                         }
2421                                 }
2422                                 /* If there are still Modifications left, put the opattrs
2423                                  * back, and let be_modify run. Otherwise, append the opattrs
2424                                  * to the orr_modlist.
2425                                  */
2426                                 if ( dni.mods ) {
2427                                         mod = dni.mods;
2428                                         /* don't set a CSN for the rename op */
2429                                         if ( syncCSN )
2430                                                 slap_graduate_commit_csn( op );
2431                                 } else {
2432                                         mod = op->orr_modlist;
2433                                         just_rename = 1;
2434                                 }
2435                                 for ( ; mod->sml_next; mod=mod->sml_next );
2436                                 mod->sml_next = m2;
2437                         }
2438                         op->o_bd = si->si_wbe;
2439                         rc = op->o_bd->be_modrdn( op, &rs_modify );
2440                         op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
2441                         op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
2442
2443                         slap_mods_free( op->orr_modlist, 1 );
2444                         Debug( LDAP_DEBUG_SYNC,
2445                                         "syncrepl_entry: %s be_modrdn %s (%d)\n", 
2446                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2447                         op->o_bd = be;
2448                         /* Renamed entries may still have other mods so just fallthru */
2449                         op->o_req_dn = entry->e_name;
2450                         op->o_req_ndn = entry->e_nname;
2451                         /* Use CSN on the modify */
2452                         if ( just_rename )
2453                                 syncCSN = NULL;
2454                         else if ( syncCSN )
2455                                 slap_queue_csn( op, syncCSN );
2456                 }
2457                 if ( dni.mods ) {
2458                         op->o_tag = LDAP_REQ_MODIFY;
2459                         op->orm_modlist = dni.mods;
2460                         op->orm_no_opattrs = 1;
2461                         op->o_bd = si->si_wbe;
2462
2463                         rc = op->o_bd->be_modify( op, &rs_modify );
2464                         slap_mods_free( op->orm_modlist, 1 );
2465                         op->orm_no_opattrs = 0;
2466                         Debug( LDAP_DEBUG_SYNC,
2467                                         "syncrepl_entry: %s be_modify %s (%d)\n", 
2468                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2469                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2470                                 Debug( LDAP_DEBUG_ANY,
2471                                         "syncrepl_entry: %s be_modify failed (%d)\n",
2472                                         si->si_ridtxt, rs_modify.sr_err, 0 );
2473                         }
2474                         syncCSN = NULL;
2475                         op->o_bd = be;
2476                 } else if ( !dni.renamed ) {
2477                         Debug( LDAP_DEBUG_SYNC,
2478                                         "syncrepl_entry: %s entry unchanged, ignored (%s)\n", 
2479                                         si->si_ridtxt, op->o_req_dn.bv_val, 0 );
2480                         if ( syncCSN ) {
2481                                 slap_graduate_commit_csn( op );
2482                                 syncCSN = NULL;
2483                         }
2484                 }
2485                 goto done;
2486         case LDAP_SYNC_DELETE :
2487                 if ( !BER_BVISNULL( &dni.dn ) ) {
2488                         op->o_req_dn = dni.dn;
2489                         op->o_req_ndn = dni.ndn;
2490                         op->o_tag = LDAP_REQ_DELETE;
2491                         op->o_bd = si->si_wbe;
2492                         rc = op->o_bd->be_delete( op, &rs_delete );
2493                         Debug( LDAP_DEBUG_SYNC,
2494                                         "syncrepl_entry: %s be_delete %s (%d)\n", 
2495                                         si->si_ridtxt, op->o_req_dn.bv_val, rc );
2496
2497                         while ( rs_delete.sr_err == LDAP_SUCCESS
2498                                 && op->o_delete_glue_parent ) {
2499                                 op->o_delete_glue_parent = 0;
2500                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2501                                         slap_callback cb = { NULL };
2502                                         cb.sc_response = slap_null_cb;
2503                                         dnParent( &op->o_req_ndn, &pdn );
2504                                         op->o_req_dn = pdn;
2505                                         op->o_req_ndn = pdn;
2506                                         op->o_callback = &cb;
2507                                         op->o_bd->be_delete( op, &rs_delete );
2508                                 } else {
2509                                         break;
2510                                 }
2511                         }
2512                         syncCSN = NULL;
2513                         op->o_bd = be;
2514                 }
2515                 goto done;
2516
2517         default :
2518                 Debug( LDAP_DEBUG_ANY,
2519                         "syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
2520                 goto done;
2521         }
2522
2523 done:
2524         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2525                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2526                 BER_BVZERO( &syncUUID_strrep );
2527         }
2528         if ( !BER_BVISNULL( &dni.ndn ) ) {
2529                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2530         }
2531         if ( !BER_BVISNULL( &dni.dn ) ) {
2532                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2533         }
2534         if ( entry ) {
2535                 entry_free( entry );
2536         }
2537         if ( syncCSN ) {
2538                 slap_graduate_commit_csn( op );
2539         }
2540         if ( !BER_BVISNULL( &op->o_csn ) && freecsn ) {
2541                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2542         }
2543         BER_BVZERO( &op->o_csn );
2544         return rc;
2545 }
2546
2547 static struct berval gcbva[] = {
2548         BER_BVC("top"),
2549         BER_BVC("glue"),
2550         BER_BVNULL
2551 };
2552
2553 #define NP_DELETE_ONE   2
2554
2555 static void
2556 syncrepl_del_nonpresent(
2557         Operation *op,
2558         syncinfo_t *si,
2559         BerVarray uuids,
2560         struct sync_cookie *sc,
2561         int m )
2562 {
2563         Backend* be = op->o_bd;
2564         slap_callback   cb = { NULL };
2565         SlapReply       rs_search = {REP_RESULT};
2566         SlapReply       rs_delete = {REP_RESULT};
2567         SlapReply       rs_modify = {REP_RESULT};
2568         struct nonpresent_entry *np_list, *np_prev;
2569         int rc;
2570         AttributeName   an[2];
2571
2572         struct berval pdn = BER_BVNULL;
2573         struct berval csn;
2574
2575         op->o_req_dn = si->si_base;
2576         op->o_req_ndn = si->si_base;
2577
2578         cb.sc_response = nonpresent_callback;
2579         cb.sc_private = si;
2580
2581         op->o_callback = &cb;
2582         op->o_tag = LDAP_REQ_SEARCH;
2583         op->ors_scope = si->si_scope;
2584         op->ors_deref = LDAP_DEREF_NEVER;
2585         op->o_time = slap_get_time();
2586         op->ors_tlimit = SLAP_NO_LIMIT;
2587
2588
2589         if ( uuids ) {
2590                 Filter uf;
2591                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
2592                 int i;
2593
2594                 op->ors_attrsonly = 1;
2595                 op->ors_attrs = slap_anlist_no_attrs;
2596                 op->ors_limit = NULL;
2597                 op->ors_filter = &uf;
2598
2599                 uf.f_ava = &eq;
2600                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2601                 uf.f_next = NULL;
2602                 uf.f_choice = LDAP_FILTER_EQUALITY;
2603                 si->si_refreshDelete |= NP_DELETE_ONE;
2604
2605                 for (i=0; uuids[i].bv_val; i++) {
2606                         op->ors_slimit = 1;
2607                         uf.f_av_value = uuids[i];
2608                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2609                         rc = be->be_search( op, &rs_search );
2610                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2611                 }
2612                 si->si_refreshDelete ^= NP_DELETE_ONE;
2613         } else {
2614                 Filter *cf, *of;
2615                 Filter mmf[2];
2616                 AttributeAssertion mmaa;
2617
2618                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2619                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2620                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2621                 op->ors_attrs = an;
2622                 op->ors_slimit = SLAP_NO_LIMIT;
2623                 op->ors_tlimit = SLAP_NO_LIMIT;
2624                 op->ors_limit = NULL;
2625                 op->ors_attrsonly = 0;
2626                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2627                 /* In multimaster, updates can continue to arrive while
2628                  * we're searching. Limit the search result to entries
2629                  * older than our newest cookie CSN.
2630                  */
2631                 if ( SLAP_MULTIMASTER( op->o_bd )) {
2632                         Filter *f;
2633                         int i;
2634
2635                         f = mmf;
2636                         f->f_choice = LDAP_FILTER_AND;
2637                         f->f_next = op->ors_filter;
2638                         f->f_and = f+1;
2639                         of = f->f_and;
2640                         f = of;
2641                         f->f_choice = LDAP_FILTER_LE;
2642                         f->f_ava = &mmaa;
2643                         f->f_av_desc = slap_schema.si_ad_entryCSN;
2644                         f->f_next = NULL;
2645                         BER_BVZERO( &f->f_av_value );
2646                         for ( i=0; i<sc->numcsns; i++ ) {
2647                                 if ( ber_bvcmp( &sc->ctxcsn[i], &f->f_av_value ) > 0 )
2648                                         f->f_av_value = sc->ctxcsn[i];
2649                         }
2650                         of = op->ors_filter;
2651                         op->ors_filter = mmf;
2652                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2653                 } else {
2654                         cf = NULL;
2655                         op->ors_filterstr = si->si_filterstr;
2656                 }
2657                 op->o_nocaching = 1;
2658
2659
2660                 rc = be->be_search( op, &rs_search );
2661                 if ( SLAP_MULTIMASTER( op->o_bd )) {
2662                         op->ors_filter = of;
2663                 }
2664                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter, 1 );
2665                 if ( op->ors_filterstr.bv_val != si->si_filterstr.bv_val ) {
2666                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2667                 }
2668
2669         }
2670
2671         op->o_nocaching = 0;
2672
2673         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2674
2675                 if ( sc->ctxcsn && !BER_BVISNULL( &sc->ctxcsn[m] ) ) {
2676                         csn = sc->ctxcsn[m];
2677                 } else {
2678                         csn = si->si_syncCookie.ctxcsn[0];
2679                 }
2680
2681                 op->o_bd = si->si_wbe;
2682                 slap_queue_csn( op, &csn );
2683
2684                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2685                 while ( np_list != NULL ) {
2686                         LDAP_LIST_REMOVE( np_list, npe_link );
2687                         np_prev = np_list;
2688                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2689                         op->o_tag = LDAP_REQ_DELETE;
2690                         op->o_callback = &cb;
2691                         cb.sc_response = null_callback;
2692                         cb.sc_private = si;
2693                         op->o_req_dn = *np_prev->npe_name;
2694                         op->o_req_ndn = *np_prev->npe_nname;
2695                         rc = op->o_bd->be_delete( op, &rs_delete );
2696                         Debug( LDAP_DEBUG_SYNC,
2697                                 "syncrepl_del_nonpresent: %s be_delete %s (%d)\n", 
2698                                 si->si_ridtxt, op->o_req_dn.bv_val, rc );
2699
2700                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2701                                 Modifications mod1, mod2;
2702                                 mod1.sml_op = LDAP_MOD_REPLACE;
2703                                 mod1.sml_flags = 0;
2704                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2705                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2706                                 mod1.sml_numvals = 2;
2707                                 mod1.sml_values = &gcbva[0];
2708                                 mod1.sml_nvalues = NULL;
2709                                 mod1.sml_next = &mod2;
2710
2711                                 mod2.sml_op = LDAP_MOD_REPLACE;
2712                                 mod2.sml_flags = 0;
2713                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2714                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2715                                 mod2.sml_numvals = 1;
2716                                 mod2.sml_values = &gcbva[1];
2717                                 mod2.sml_nvalues = NULL;
2718                                 mod2.sml_next = NULL;
2719
2720                                 op->o_tag = LDAP_REQ_MODIFY;
2721                                 op->orm_modlist = &mod1;
2722
2723                                 rc = op->o_bd->be_modify( op, &rs_modify );
2724                                 if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2725                         }
2726
2727                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2728                                         op->o_delete_glue_parent ) {
2729                                 op->o_delete_glue_parent = 0;
2730                                 if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2731                                         slap_callback cb = { NULL };
2732                                         cb.sc_response = slap_null_cb;
2733                                         dnParent( &op->o_req_ndn, &pdn );
2734                                         op->o_req_dn = pdn;
2735                                         op->o_req_ndn = pdn;
2736                                         op->o_callback = &cb;
2737                                         /* give it a root privil ? */
2738                                         op->o_bd->be_delete( op, &rs_delete );
2739                                 } else {
2740                                         break;
2741                                 }
2742                         }
2743
2744                         op->o_delete_glue_parent = 0;
2745
2746                         ber_bvfree( np_prev->npe_name );
2747                         ber_bvfree( np_prev->npe_nname );
2748                         ch_free( np_prev );
2749
2750                         if ( slapd_shutdown ) {
2751                                 break;
2752                         }
2753                 }
2754
2755                 slap_graduate_commit_csn( op );
2756                 op->o_bd = be;
2757
2758                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2759                 BER_BVZERO( &op->o_csn );
2760         }
2761
2762         return;
2763 }
2764
2765 int
2766 syncrepl_add_glue(
2767         Operation* op,
2768         Entry *e )
2769 {
2770         Backend *be = op->o_bd;
2771         slap_callback cb = { NULL };
2772         Attribute       *a;
2773         int     rc;
2774         int suffrdns;
2775         int i;
2776         struct berval dn = BER_BVNULL;
2777         struct berval ndn = BER_BVNULL;
2778         Entry   *glue;
2779         SlapReply       rs_add = {REP_RESULT};
2780         struct berval   ptr, nptr;
2781         char            *comma;
2782
2783         op->o_tag = LDAP_REQ_ADD;
2784         op->o_callback = &cb;
2785         cb.sc_response = null_callback;
2786         cb.sc_private = NULL;
2787
2788         dn = e->e_name;
2789         ndn = e->e_nname;
2790
2791         /* count RDNs in suffix */
2792         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2793                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2794                         comma++;
2795                         ptr.bv_len -= comma - ptr.bv_val;
2796                         ptr.bv_val = comma;
2797                         i++;
2798                 }
2799                 suffrdns = i;
2800         } else {
2801                 /* suffix is "" */
2802                 suffrdns = 0;
2803         }
2804
2805         /* Start with BE suffix */
2806         ptr = dn;
2807         for ( i = 0; i < suffrdns; i++ ) {
2808                 comma = ber_bvrchr( &ptr, ',' );
2809                 if ( comma != NULL ) {
2810                         ptr.bv_len = comma - ptr.bv_val;
2811                 } else {
2812                         ptr.bv_len = 0;
2813                         break;
2814                 }
2815         }
2816         
2817         if ( !BER_BVISEMPTY( &ptr ) ) {
2818                 dn.bv_len -= ptr.bv_len + 1;
2819                 dn.bv_val += ptr.bv_len + 1;
2820         }
2821
2822         /* the normalizedDNs are always the same length, no counting
2823          * required.
2824          */
2825         nptr = ndn;
2826         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2827                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2828                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2829
2830                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2831
2832         } else {
2833                 nptr.bv_len = 0;
2834         }
2835
2836         while ( ndn.bv_val > e->e_nname.bv_val ) {
2837                 glue = entry_alloc();
2838                 ber_dupbv( &glue->e_name, &dn );
2839                 ber_dupbv( &glue->e_nname, &ndn );
2840
2841                 a = attr_alloc( slap_schema.si_ad_objectClass );
2842
2843                 a->a_numvals = 2;
2844                 a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
2845                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2846                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2847                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2848
2849                 a->a_nvals = a->a_vals;
2850
2851                 a->a_next = glue->e_attrs;
2852                 glue->e_attrs = a;
2853
2854                 a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
2855
2856                 a->a_numvals = 1;
2857                 a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
2858                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2859                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2860
2861                 a->a_nvals = a->a_vals;
2862
2863                 a->a_next = glue->e_attrs;
2864                 glue->e_attrs = a;
2865
2866                 op->o_req_dn = glue->e_name;
2867                 op->o_req_ndn = glue->e_nname;
2868                 op->ora_e = glue;
2869                 rc = be->be_add ( op, &rs_add );
2870                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2871                         if ( op->ora_e == glue )
2872                                 be_entry_release_w( op, glue );
2873                 } else {
2874                 /* incl. ALREADY EXIST */
2875                         entry_free( glue );
2876                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2877                                 entry_free( e );
2878                                 return rc;
2879                         }
2880                 }
2881
2882                 /* Move to next child */
2883                 comma = ber_bvrchr( &ptr, ',' );
2884                 if ( comma == NULL ) {
2885                         break;
2886                 }
2887                 ptr.bv_len = comma - ptr.bv_val;
2888                 
2889                 dn.bv_val = ++comma;
2890                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2891
2892                 comma = ber_bvrchr( &nptr, ',' );
2893                 assert( comma != NULL );
2894                 nptr.bv_len = comma - nptr.bv_val;
2895
2896                 ndn.bv_val = ++comma;
2897                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2898         }
2899
2900         op->o_req_dn = e->e_name;
2901         op->o_req_ndn = e->e_nname;
2902         op->ora_e = e;
2903         rc = be->be_add ( op, &rs_add );
2904         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2905                 if ( op->ora_e == e )
2906                         be_entry_release_w( op, e );
2907         } else {
2908                 entry_free( e );
2909         }
2910
2911         return rc;
2912 }
2913
2914 static int
2915 syncrepl_updateCookie(
2916         syncinfo_t *si,
2917         Operation *op,
2918         struct berval *pdn,
2919         struct sync_cookie *syncCookie )
2920 {
2921         Backend *be = op->o_bd;
2922         Modifications mod;
2923         struct berval first = BER_BVNULL;
2924 #ifdef CHECK_CSN
2925         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
2926 #endif
2927
2928         int rc, i, j;
2929         ber_len_t len;
2930
2931         slap_callback cb = { NULL };
2932         SlapReply       rs_modify = {REP_RESULT};
2933
2934         mod.sml_op = LDAP_MOD_REPLACE;
2935         mod.sml_desc = slap_schema.si_ad_contextCSN;
2936         mod.sml_type = mod.sml_desc->ad_cname;
2937         mod.sml_flags = SLAP_MOD_INTERNAL;
2938         mod.sml_nvalues = NULL;
2939         mod.sml_next = NULL;
2940
2941         ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
2942
2943 #ifdef CHECK_CSN
2944         for ( i=0; i<syncCookie->numcsns; i++ ) {
2945                 assert( !syn->ssyn_validate( syn, syncCookie->ctxcsn+i ));
2946         }
2947         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
2948                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
2949         }
2950 #endif
2951
2952         /* clone the cookieState CSNs so we can Replace the whole thing */
2953         mod.sml_numvals = si->si_cookieState->cs_num;
2954         mod.sml_values = op->o_tmpalloc(( mod.sml_numvals+1 )*sizeof(struct berval), op->o_tmpmemctx );
2955         for ( i=0; i<mod.sml_numvals; i++ )
2956                 mod.sml_values[i] = si->si_cookieState->cs_vals[i];
2957         BER_BVZERO( &mod.sml_values[i] );
2958
2959         /* find any CSNs in the syncCookie that are newer than the cookieState */
2960         for ( i=0; i<syncCookie->numcsns; i++ ) {
2961                 for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
2962                         if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
2963                                 continue;
2964                         len = syncCookie->ctxcsn[i].bv_len;
2965                         if ( len > si->si_cookieState->cs_vals[j].bv_len )
2966                                 len = si->si_cookieState->cs_vals[j].bv_len;
2967                         if ( memcmp( syncCookie->ctxcsn[i].bv_val,
2968                                 si->si_cookieState->cs_vals[j].bv_val, len ) > 0 ) {
2969                                 mod.sml_values[j] = syncCookie->ctxcsn[i];
2970                                 if ( BER_BVISNULL( &first ) ) {
2971                                         first = syncCookie->ctxcsn[i];
2972
2973                                 } else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
2974                                 {
2975                                         first = syncCookie->ctxcsn[i];
2976                                 }
2977                         }
2978                         break;
2979                 }
2980                 /* there was no match for this SID, it's a new CSN */
2981                 if ( j == si->si_cookieState->cs_num ) {
2982                         mod.sml_values = op->o_tmprealloc( mod.sml_values,
2983                                 ( mod.sml_numvals+2 )*sizeof(struct berval), op->o_tmpmemctx );
2984                         mod.sml_values[mod.sml_numvals++] = syncCookie->ctxcsn[i];
2985                         BER_BVZERO( &mod.sml_values[mod.sml_numvals] );
2986                         if ( BER_BVISNULL( &first ) ) {
2987                                 first = syncCookie->ctxcsn[i];
2988                         } else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
2989                         {
2990                                 first = syncCookie->ctxcsn[i];
2991                         }
2992                 }
2993         }
2994         /* Should never happen, ITS#5065 */
2995         if ( BER_BVISNULL( &first )) {
2996                 ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
2997                 op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
2998                 return 0;
2999         }
3000         op->o_bd = si->si_wbe;
3001         slap_queue_csn( op, &first );
3002
3003         op->o_tag = LDAP_REQ_MODIFY;
3004
3005         cb.sc_response = null_callback;
3006         cb.sc_private = si;
3007
3008         op->o_callback = &cb;
3009         op->o_req_dn = op->o_bd->be_suffix[0];
3010         op->o_req_ndn = op->o_bd->be_nsuffix[0];
3011
3012         /* update contextCSN */
3013         op->o_dont_replicate = 1;
3014
3015         op->orm_modlist = &mod;
3016         op->orm_no_opattrs = 1;
3017         rc = op->o_bd->be_modify( op, &rs_modify );
3018         op->orm_no_opattrs = 0;
3019         op->o_dont_replicate = 0;
3020
3021         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
3022                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
3023                 slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
3024                 /* If we replaced any old values */
3025                 for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3026                         if ( mod.sml_values[i].bv_val != si->si_cookieState->cs_vals[i].bv_val )
3027                                         ber_bvreplace( &si->si_cookieState->cs_vals[i],
3028                                                 &mod.sml_values[i] );
3029                 }
3030                 /* Handle any added values */
3031                 if ( i < mod.sml_numvals ) {
3032                         si->si_cookieState->cs_num = mod.sml_numvals;
3033                         value_add( &si->si_cookieState->cs_vals, &mod.sml_values[i] );
3034                         free( si->si_cookieState->cs_sids );
3035                         si->si_cookieState->cs_sids = slap_parse_csn_sids(
3036                                 si->si_cookieState->cs_vals, si->si_cookieState->cs_num, NULL );
3037                 }
3038
3039                 si->si_cookieState->cs_age++;
3040                 si->si_cookieAge = si->si_cookieState->cs_age;
3041         } else {
3042                 Debug( LDAP_DEBUG_ANY,
3043                         "syncrepl_updateCookie: %s be_modify failed (%d)\n",
3044                         si->si_ridtxt, rs_modify.sr_err, 0 );
3045         }
3046         ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3047
3048         op->o_bd = be;
3049         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3050         BER_BVZERO( &op->o_csn );
3051         if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
3052         op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3053
3054 #ifdef CHECK_CSN
3055         for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3056                 assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3057         }
3058 #endif
3059
3060         return rc;
3061 }
3062
3063 static void
3064 attr_cmp( Operation *op, Attribute *old, Attribute *new,
3065         Modifications ***mret, Modifications ***mcur )
3066 {
3067         int i, j;
3068         Modifications *mod, **modtail;
3069
3070         modtail = *mret;
3071
3072         if ( old ) {
3073                 int n, o, nn, no;
3074                 struct berval **adds, **dels;
3075                 /* count old and new */
3076                 for ( o=0; old->a_vals[o].bv_val; o++ ) ;
3077                 for ( n=0; new->a_vals[n].bv_val; n++ ) ;
3078
3079                 /* there MUST be both old and new values */
3080                 assert( o != 0 );
3081                 assert( n != 0 );
3082                 j = 0;
3083
3084                 adds = op->o_tmpalloc( sizeof(struct berval *) * n, op->o_tmpmemctx );
3085                 dels = op->o_tmpalloc( sizeof(struct berval *) * o, op->o_tmpmemctx );
3086
3087                 for ( i=0; i<o; i++ ) dels[i] = &old->a_vals[i];
3088                 for ( i=0; i<n; i++ ) adds[i] = &new->a_vals[i];
3089
3090                 nn = n; no = o;
3091
3092                 for ( i=0; i<o; i++ ) {
3093                         for ( j=0; j<n; j++ ) {
3094                                 if ( !adds[j] )
3095                                         continue;
3096                                 if ( bvmatch( dels[i], adds[j] ) ) {
3097                                         no--;
3098                                         nn--;
3099                                         adds[j] = NULL;
3100                                         dels[i] = NULL;
3101                                         break;
3102                                 }
3103                         }
3104                 }
3105
3106                 /* Don't delete/add an objectClass, always use the replace op.
3107                  * Modify would fail if provider has replaced entry with a new,
3108                  * and the new explicitly includes a superior of a class that was
3109                  * only included implicitly in the old entry.  Ref ITS#5517.
3110                  *
3111                  * Also use replace op if attr has no equality matching rule.
3112                  * (ITS#5781)
3113                  */
3114                 if ( nn && no < o &&
3115                         ( old->a_desc == slap_schema.si_ad_objectClass ||
3116                          !old->a_desc->ad_type->sat_equality ))
3117                         no = o;
3118
3119                 i = j;
3120                 /* all old values were deleted, just use the replace op */
3121                 if ( no == o ) {
3122                         i = j-1;
3123                 } else if ( no ) {
3124                 /* delete some values */
3125                         mod = ch_malloc( sizeof( Modifications ) );
3126                         mod->sml_op = LDAP_MOD_DELETE;
3127                         mod->sml_flags = 0;
3128                         mod->sml_desc = old->a_desc;
3129                         mod->sml_type = mod->sml_desc->ad_cname;
3130                         mod->sml_numvals = no;
3131                         mod->sml_values = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3132                         if ( old->a_vals != old->a_nvals ) {
3133                                 mod->sml_nvalues = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3134                         } else {
3135                                 mod->sml_nvalues = NULL;
3136                         }
3137                         j = 0;
3138                         for ( i = 0; i < o; i++ ) {
3139                                 if ( !dels[i] ) continue;
3140                                 ber_dupbv( &mod->sml_values[j], &old->a_vals[i] );
3141                                 if ( mod->sml_nvalues ) {
3142                                         ber_dupbv( &mod->sml_nvalues[j], &old->a_nvals[i] );
3143                                 }
3144                                 j++;
3145                         }
3146                         BER_BVZERO( &mod->sml_values[j] );
3147                         if ( mod->sml_nvalues ) {
3148                                 BER_BVZERO( &mod->sml_nvalues[j] );
3149                         }
3150                         *modtail = mod;
3151                         modtail = &mod->sml_next;
3152                         i = j;
3153                 }
3154                 op->o_tmpfree( dels, op->o_tmpmemctx );
3155                 /* some values were added */
3156                 if ( nn && no < o ) {
3157                         mod = ch_malloc( sizeof( Modifications ) );
3158                         mod->sml_op = LDAP_MOD_ADD;
3159                         mod->sml_flags = 0;
3160                         mod->sml_desc = old->a_desc;
3161                         mod->sml_type = mod->sml_desc->ad_cname;
3162                         mod->sml_numvals = nn;
3163                         mod->sml_values = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3164                         if ( old->a_vals != old->a_nvals ) {
3165                                 mod->sml_nvalues = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3166                         } else {
3167                                 mod->sml_nvalues = NULL;
3168                         }
3169                         j = 0;
3170                         for ( i = 0; i < n; i++ ) {
3171                                 if ( !adds[i] ) continue;
3172                                 ber_dupbv( &mod->sml_values[j], &new->a_vals[i] );
3173                                 if ( mod->sml_nvalues ) {
3174                                         ber_dupbv( &mod->sml_nvalues[j], &new->a_nvals[i] );
3175                                 }
3176                                 j++;
3177                         }
3178                         BER_BVZERO( &mod->sml_values[j] );
3179                         if ( mod->sml_nvalues ) {
3180                                 BER_BVZERO( &mod->sml_nvalues[j] );
3181                         }
3182                         *modtail = mod;
3183                         modtail = &mod->sml_next;
3184                         i = j;
3185                 }
3186                 op->o_tmpfree( adds, op->o_tmpmemctx );
3187         } else {
3188                 /* new attr, just use the new mod */
3189                 i = 0;
3190                 j = 1;
3191         }
3192         /* advance to next element */
3193         mod = **mcur;
3194         if ( mod ) {
3195                 if ( i != j ) {
3196                         **mcur = mod->sml_next;
3197                         *modtail = mod;
3198                         modtail = &mod->sml_next;
3199                 } else {
3200                         *mcur = &mod->sml_next;
3201                 }
3202         }
3203         *mret = modtail;
3204 }
3205
3206 static int
3207 dn_callback(
3208         Operation*      op,
3209         SlapReply*      rs )
3210 {
3211         dninfo *dni = op->o_callback->sc_private;
3212
3213         if ( rs->sr_type == REP_SEARCH ) {
3214                 if ( !BER_BVISNULL( &dni->dn ) ) {
3215                         Debug( LDAP_DEBUG_ANY,
3216                                 "dn_callback : consistency error - "
3217                                 "entryUUID is not unique\n", 0, 0, 0 );
3218                 } else {
3219                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
3220                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
3221                         /* If there is a new entry, see if it differs from the old.
3222                          * We compare the non-normalized values so that cosmetic changes
3223                          * in the provider are always propagated.
3224                          */
3225                         if ( dni->new_entry ) {
3226                                 Modifications **modtail, **ml;
3227                                 Attribute *old, *new;
3228                                 struct berval old_rdn, new_rdn;
3229                                 struct berval old_p, new_p;
3230                                 int is_ctx, new_sup = 0;
3231
3232                                 /* If old entry is not a glue entry, make sure new entry
3233                                  * is actually newer than old entry
3234                                  */
3235                                 if ( !is_entry_glue( rs->sr_entry )) {
3236                                         old = attr_find( rs->sr_entry->e_attrs,
3237                                                 slap_schema.si_ad_entryCSN );
3238                                         new = attr_find( dni->new_entry->e_attrs,
3239                                                 slap_schema.si_ad_entryCSN );
3240                                         if ( new && old ) {
3241                                                 int rc;
3242                                                 ber_len_t len = old->a_vals[0].bv_len;
3243                                                 if ( len > new->a_vals[0].bv_len )
3244                                                         len = new->a_vals[0].bv_len;
3245                                                 rc = memcmp( old->a_vals[0].bv_val,
3246                                                         new->a_vals[0].bv_val, len );
3247                                                 if ( rc > 0 ) {
3248                                                         Debug( LDAP_DEBUG_SYNC,
3249                                                                 "dn_callback : new entry is older than ours "
3250                                                                 "%s ours %s, new %s\n",
3251                                                                 rs->sr_entry->e_name.bv_val,
3252                                                                 old->a_vals[0].bv_val,
3253                                                                 new->a_vals[0].bv_val );
3254                                                         return LDAP_SUCCESS;
3255                                                 } else if ( rc == 0 ) {
3256                                                         Debug( LDAP_DEBUG_SYNC,
3257                                                                 "dn_callback : entries have identical CSN "
3258                                                                 "%s %s\n",
3259                                                                 rs->sr_entry->e_name.bv_val,
3260                                                                 old->a_vals[0].bv_val, 0 );
3261                                                         return LDAP_SUCCESS;
3262                                                 }
3263                                         }
3264                                 }
3265
3266                                 is_ctx = dn_match( &rs->sr_entry->e_nname,
3267                                         &op->o_bd->be_nsuffix[0] );
3268
3269                                 /* Did the DN change?
3270                                  * case changes in the parent are ignored,
3271                                  * we only want to know if the RDN was
3272                                  * actually changed.
3273                                  */
3274                                 dnRdn( &rs->sr_entry->e_name, &old_rdn );
3275                                 dnRdn( &dni->new_entry->e_name, &new_rdn );
3276                                 dnParent( &rs->sr_entry->e_nname, &old_p );
3277                                 dnParent( &dni->new_entry->e_nname, &new_p );
3278
3279                                 new_sup = !dn_match( &old_p, &new_p );
3280                                 if ( !dn_match( &old_rdn, &new_rdn ) || new_sup )
3281                                 {
3282                                         struct berval oldRDN, oldVal;
3283                                         AttributeDescription *ad = NULL;
3284                                         int oldpos, newpos;
3285                                         Attribute *a;
3286
3287                                         dni->renamed = 1;
3288                                         if ( new_sup )
3289                                                 dni->nnewSup = new_p;
3290
3291                                         /* See if the oldRDN was deleted */
3292                                         dnRdn( &rs->sr_entry->e_nname, &oldRDN );
3293                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
3294                                         oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
3295                                                 oldRDN.bv_val );
3296                                         oldRDN.bv_len -= oldVal.bv_len + 1;
3297                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
3298                                         dni->oldDesc = ad;
3299                                         for ( oldpos=0, a=rs->sr_entry->e_attrs;
3300                                                 a && a->a_desc != ad; oldpos++, a=a->a_next );
3301                                         dni->oldNattr = a;
3302                                         for ( newpos=0, a=dni->new_entry->e_attrs;
3303                                                 a && a->a_desc != ad; newpos++, a=a->a_next );
3304                                         if ( !a || oldpos != newpos || attr_valfind( a,
3305                                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
3306                                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
3307                                                 SLAP_MR_VALUE_OF_SYNTAX,
3308                                                 &oldVal, NULL, op->o_tmpmemctx ) != LDAP_SUCCESS )
3309                                         {
3310                                                 dni->delOldRDN = 1;
3311                                         }
3312                                         /* Get the newRDN's desc */
3313                                         dnRdn( &dni->new_entry->e_nname, &oldRDN );
3314                                         oldVal.bv_val = strchr(oldRDN.bv_val, '=');
3315                                         oldRDN.bv_len = oldVal.bv_val - oldRDN.bv_val;
3316                                         ad = NULL;
3317                                         slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
3318                                         dni->newDesc = ad;
3319
3320                                         /* A ModDN has happened, but in Refresh mode other
3321                                          * changes may have occurred before we picked it up.
3322                                          * So fallthru to regular Modify processing.
3323                                          */
3324                                 }
3325
3326                                 modtail = &dni->mods;
3327                                 ml = dni->modlist;
3328
3329                                 /* We assume that attributes are saved in the same order
3330                                  * in the remote and local databases. So if we walk through
3331                                  * the attributeDescriptions one by one they should match in
3332                                  * lock step. If not, look for an add or delete.
3333                                  */
3334                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
3335                                                 old && new; )
3336                                 {
3337                                         /* If we've seen this before, use its mod now */
3338                                         if ( new->a_flags & SLAP_ATTR_IXADD ) {
3339                                                 attr_cmp( op, NULL, new, &modtail, &ml );
3340                                                 new = new->a_next;
3341                                                 continue;
3342                                         }
3343                                         /* Skip contextCSN */
3344                                         if ( is_ctx && old->a_desc ==
3345                                                 slap_schema.si_ad_contextCSN ) {
3346                                                 old = old->a_next;
3347                                                 continue;
3348                                         }
3349
3350                                         if ( old->a_desc != new->a_desc ) {
3351                                                 Modifications *mod;
3352                                                 Attribute *tmp;
3353
3354                                                 /* If it's just been re-added later,
3355                                                  * remember that we've seen it.
3356                                                  */
3357                                                 tmp = attr_find( new, old->a_desc );
3358                                                 if ( tmp ) {
3359                                                         tmp->a_flags |= SLAP_ATTR_IXADD;
3360                                                 } else {
3361                                                         /* If it's a new attribute, pull it in.
3362                                                          */
3363                                                         tmp = attr_find( old, new->a_desc );
3364                                                         if ( !tmp ) {
3365                                                                 attr_cmp( op, NULL, new, &modtail, &ml );
3366                                                                 new = new->a_next;
3367                                                                 continue;
3368                                                         }
3369                                                         /* Delete old attr */
3370                                                         mod = ch_malloc( sizeof( Modifications ) );
3371                                                         mod->sml_op = LDAP_MOD_DELETE;
3372                                                         mod->sml_flags = 0;
3373                                                         mod->sml_desc = old->a_desc;
3374                                                         mod->sml_type = mod->sml_desc->ad_cname;
3375                                                         mod->sml_numvals = 0;
3376                                                         mod->sml_values = NULL;
3377                                                         mod->sml_nvalues = NULL;
3378                                                         *modtail = mod;
3379                                                         modtail = &mod->sml_next;
3380                                                 }
3381                                                 old = old->a_next;
3382                                                 continue;
3383                                         }
3384                                         /* kludge - always update modifiersName so that it
3385                                          * stays co-located with the other mod opattrs. But only
3386                                          * if we know there are other valid mods.
3387                                          */
3388                                         if ( dni->mods && ( old->a_desc == slap_schema.si_ad_modifiersName ||
3389                                                 old->a_desc == slap_schema.si_ad_modifyTimestamp ))
3390                                                 attr_cmp( op, NULL, new, &modtail, &ml );
3391                                         else
3392                                                 attr_cmp( op, old, new, &modtail, &ml );
3393                                         new = new->a_next;
3394                                         old = old->a_next;
3395                                 }
3396                                 *modtail = *ml;
3397                                 *ml = NULL;
3398                         }
3399                 }
3400         } else if ( rs->sr_type == REP_RESULT ) {
3401                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
3402                         Debug( LDAP_DEBUG_ANY,
3403                                 "dn_callback : consistency error - "
3404                                 "entryUUID is not unique\n", 0, 0, 0 );
3405                 }
3406         }
3407
3408         return LDAP_SUCCESS;
3409 }
3410
3411 static int
3412 nonpresent_callback(
3413         Operation*      op,
3414         SlapReply*      rs )
3415 {
3416         syncinfo_t *si = op->o_callback->sc_private;
3417         Attribute *a;
3418         int count = 0;
3419         struct berval* present_uuid = NULL;
3420         struct nonpresent_entry *np_entry;
3421
3422         if ( rs->sr_type == REP_RESULT ) {
3423                 count = avl_free( si->si_presentlist, ch_free );
3424                 si->si_presentlist = NULL;
3425
3426         } else if ( rs->sr_type == REP_SEARCH ) {
3427                 if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
3428                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
3429
3430                         if ( a ) {
3431                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
3432                                         syncuuid_cmp );
3433                         }
3434
3435                         if ( LogTest( LDAP_DEBUG_SYNC ) ) {
3436                                 char buf[sizeof("rid=999 non")];
3437
3438                                 snprintf( buf, sizeof(buf), "%s %s", si->si_ridtxt,
3439                                         present_uuid ? "" : "non" );
3440
3441                                 Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %spresent UUID %s, dn %s\n",
3442                                         buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
3443                         }
3444
3445                         if ( a == NULL ) return 0;
3446                 }
3447
3448                 if ( present_uuid == NULL ) {
3449                         np_entry = (struct nonpresent_entry *)
3450                                 ch_calloc( 1, sizeof( struct nonpresent_entry ) );
3451                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
3452                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
3453                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
3454
3455                 } else {
3456                         avl_delete( &si->si_presentlist,
3457                                 &a->a_nvals[0], syncuuid_cmp );
3458                         ch_free( present_uuid );
3459                 }
3460         }
3461         return LDAP_SUCCESS;
3462 }
3463
3464 static int
3465 null_callback(
3466         Operation*      op,
3467         SlapReply*      rs )
3468 {
3469         if ( rs->sr_err != LDAP_SUCCESS &&
3470                 rs->sr_err != LDAP_REFERRAL &&
3471                 rs->sr_err != LDAP_ALREADY_EXISTS &&
3472                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
3473                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
3474         {
3475                 Debug( LDAP_DEBUG_ANY,
3476                         "null_callback : error code 0x%x\n",
3477                         rs->sr_err, 0, 0 );
3478         }
3479         return LDAP_SUCCESS;
3480 }
3481
3482 static struct berval *
3483 slap_uuidstr_from_normalized(
3484         struct berval* uuidstr,
3485         struct berval* normalized,
3486         void *ctx )
3487 {
3488 #if 0
3489         struct berval *new;
3490         unsigned char nibble;
3491         int i, d = 0;
3492
3493         if ( normalized == NULL ) return NULL;
3494         if ( normalized->bv_len != 16 ) return NULL;
3495
3496         if ( uuidstr ) {
3497                 new = uuidstr;
3498         } else {
3499                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3500                 if ( new == NULL ) {
3501                         return NULL;
3502                 }
3503         }
3504
3505         new->bv_len = 36;
3506
3507         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3508                 if ( new != uuidstr ) {
3509                         slap_sl_free( new, ctx );
3510                 }
3511                 return NULL;
3512         }
3513
3514         for ( i = 0; i < 16; i++ ) {
3515                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
3516                         new->bv_val[(i<<1)+d] = '-';
3517                         d += 1;
3518                 }
3519
3520                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
3521                 if ( nibble < 10 ) {
3522                         new->bv_val[(i<<1)+d] = nibble + '0';
3523                 } else {
3524                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
3525                 }
3526
3527                 nibble = (normalized->bv_val[i]) & 0xF;
3528                 if ( nibble < 10 ) {
3529                         new->bv_val[(i<<1)+d+1] = nibble + '0';
3530                 } else {
3531                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
3532                 }
3533         }
3534
3535         new->bv_val[new->bv_len] = '\0';
3536         return new;
3537 #endif
3538
3539         struct berval   *new;
3540         int             rc = 0;
3541
3542         if ( normalized == NULL ) return NULL;
3543         if ( normalized->bv_len != 16 ) return NULL;
3544
3545         if ( uuidstr ) {
3546                 new = uuidstr;
3547
3548         } else {
3549                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3550                 if ( new == NULL ) {
3551                         return NULL;
3552                 }
3553         }
3554
3555         new->bv_len = 36;
3556
3557         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3558                 rc = 1;
3559                 goto done;
3560         }
3561
3562         rc = lutil_uuidstr_from_normalized( normalized->bv_val,
3563                 normalized->bv_len, new->bv_val, new->bv_len + 1 );
3564
3565 done:;
3566         if ( rc == -1 ) {
3567                 if ( new != NULL ) {
3568                         if ( new->bv_val != NULL ) {
3569                                 slap_sl_free( new->bv_val, ctx );
3570                         }
3571
3572                         if ( new != uuidstr ) {
3573                                 slap_sl_free( new, ctx );
3574                         }
3575                 }
3576                 new = NULL;
3577
3578         } else {
3579                 new->bv_len = rc;
3580         }
3581
3582         return new;
3583 }
3584
3585 static int
3586 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
3587 {
3588         const struct berval *uuid1 = v_uuid1;
3589         const struct berval *uuid2 = v_uuid2;
3590         int rc = uuid1->bv_len - uuid2->bv_len;
3591         if ( rc ) return rc;
3592         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
3593 }
3594
3595 void
3596 syncinfo_free( syncinfo_t *sie, int free_all )
3597 {
3598         syncinfo_t *si_next;
3599
3600         Debug( LDAP_DEBUG_TRACE, "syncinfo_free: %s\n",
3601                 sie->si_ridtxt, 0, 0 );
3602
3603         do {
3604                 si_next = sie->si_next;
3605
3606                 if ( sie->si_ld ) {
3607                         if ( sie->si_conn ) {
3608                                 connection_client_stop( sie->si_conn );
3609                                 sie->si_conn = NULL;
3610                         }
3611                         ldap_unbind_ext( sie->si_ld, NULL, NULL );
3612                 }
3613         
3614                 if ( sie->si_re ) {
3615                         struct re_s             *re = sie->si_re;
3616                         sie->si_re = NULL;
3617
3618                         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3619                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
3620                                 ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3621                         ldap_pvt_runqueue_remove( &slapd_rq, re );
3622                         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3623                 }
3624
3625                 ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
3626
3627                 bindconf_free( &sie->si_bindconf );
3628
3629                 if ( sie->si_filterstr.bv_val ) {
3630                         ch_free( sie->si_filterstr.bv_val );
3631                 }
3632                 if ( sie->si_logfilterstr.bv_val ) {
3633                         ch_free( sie->si_logfilterstr.bv_val );
3634                 }
3635                 if ( sie->si_base.bv_val ) {
3636                         ch_free( sie->si_base.bv_val );
3637                 }
3638                 if ( sie->si_logbase.bv_val ) {
3639                         ch_free( sie->si_logbase.bv_val );
3640                 }
3641                 if ( sie->si_attrs ) {
3642                         int i = 0;
3643                         while ( sie->si_attrs[i] != NULL ) {
3644                                 ch_free( sie->si_attrs[i] );
3645                                 i++;
3646                         }
3647                         ch_free( sie->si_attrs );
3648                 }
3649                 if ( sie->si_exattrs ) {
3650                         int i = 0;
3651                         while ( sie->si_exattrs[i] != NULL ) {
3652                                 ch_free( sie->si_exattrs[i] );
3653                                 i++;
3654                         }
3655                         ch_free( sie->si_exattrs );
3656                 }
3657                 if ( sie->si_anlist ) {
3658                         int i = 0;
3659                         while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
3660                                 ch_free( sie->si_anlist[i].an_name.bv_val );
3661                                 i++;
3662                         }
3663                         ch_free( sie->si_anlist );
3664                 }
3665                 if ( sie->si_exanlist ) {
3666                         int i = 0;
3667                         while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
3668                                 ch_free( sie->si_exanlist[i].an_name.bv_val );
3669                                 i++;
3670                         }
3671                         ch_free( sie->si_exanlist );
3672                 }
3673                 if ( sie->si_retryinterval ) {
3674                         ch_free( sie->si_retryinterval );
3675                 }
3676                 if ( sie->si_retrynum ) {
3677                         ch_free( sie->si_retrynum );
3678                 }
3679                 if ( sie->si_retrynum_init ) {
3680                         ch_free( sie->si_retrynum_init );
3681                 }
3682                 slap_sync_cookie_free( &sie->si_syncCookie, 0 );
3683                 if ( sie->si_presentlist ) {
3684                     avl_free( sie->si_presentlist, ch_free );
3685                 }
3686                 while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
3687                         struct nonpresent_entry* npe;
3688                         npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
3689                         LDAP_LIST_REMOVE( npe, npe_link );
3690                         if ( npe->npe_name ) {
3691                                 if ( npe->npe_name->bv_val ) {
3692                                         ch_free( npe->npe_name->bv_val );
3693                                 }
3694                                 ch_free( npe->npe_name );
3695                         }
3696                         if ( npe->npe_nname ) {
3697                                 if ( npe->npe_nname->bv_val ) {
3698                                         ch_free( npe->npe_nname->bv_val );
3699                                 }
3700                                 ch_free( npe->npe_nname );
3701                         }
3702                         ch_free( npe );
3703                 }
3704                 sie->si_cookieState->cs_ref--;
3705                 if ( !sie->si_cookieState->cs_ref ) {
3706                         ch_free( sie->si_cookieState->cs_sids );
3707                         ber_bvarray_free( sie->si_cookieState->cs_vals );
3708                         ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
3709                         ch_free( sie->si_cookieState );
3710                 }
3711                 ch_free( sie );
3712                 sie = si_next;
3713         } while ( free_all && si_next );
3714 }
3715
3716
3717
3718 /* NOTE: used & documented in slapd.conf(5) */
3719 #define IDSTR                   "rid"
3720 #define PROVIDERSTR             "provider"
3721 #define SCHEMASTR               "schemachecking"
3722 #define FILTERSTR               "filter"
3723 #define SEARCHBASESTR           "searchbase"
3724 #define SCOPESTR                "scope"
3725 #define ATTRSONLYSTR            "attrsonly"
3726 #define ATTRSSTR                "attrs"
3727 #define TYPESTR                 "type"
3728 #define INTERVALSTR             "interval"
3729 #define RETRYSTR                "retry"
3730 #define SLIMITSTR               "sizelimit"
3731 #define TLIMITSTR               "timelimit"
3732 #define SYNCDATASTR             "syncdata"
3733 #define LOGBASESTR              "logbase"
3734 #define LOGFILTERSTR    "logfilter"
3735
3736 /* FIXME: undocumented */
3737 #define EXATTRSSTR              "exattrs"
3738 #define MANAGEDSAITSTR          "manageDSAit"
3739
3740 /* mandatory */
3741 enum {
3742         GOT_RID                 = 0x00000001U,
3743         GOT_PROVIDER            = 0x00000002U,
3744         GOT_SCHEMACHECKING      = 0x00000004U,
3745         GOT_FILTER              = 0x00000008U,
3746         GOT_SEARCHBASE          = 0x00000010U,
3747         GOT_SCOPE               = 0x00000020U,
3748         GOT_ATTRSONLY           = 0x00000040U,
3749         GOT_ATTRS               = 0x00000080U,
3750         GOT_TYPE                = 0x00000100U,
3751         GOT_INTERVAL            = 0x00000200U,
3752         GOT_RETRY               = 0x00000400U,
3753         GOT_SLIMIT              = 0x00000800U,
3754         GOT_TLIMIT              = 0x00001000U,
3755         GOT_SYNCDATA            = 0x00002000U,
3756         GOT_LOGBASE             = 0x00004000U,
3757         GOT_LOGFILTER           = 0x00008000U,
3758         GOT_EXATTRS             = 0x00010000U,
3759         GOT_MANAGEDSAIT         = 0x00020000U,
3760         GOT_BINDCONF            = 0x00040000U,
3761
3762 /* check */
3763         GOT_REQUIRED            = (GOT_RID|GOT_PROVIDER|GOT_SEARCHBASE)
3764 };
3765
3766 static struct {
3767         struct berval key;
3768         int val;
3769 } scopes[] = {
3770         { BER_BVC("base"), LDAP_SCOPE_BASE },
3771         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
3772         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
3773         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
3774         { BER_BVC("subord"), LDAP_SCOPE_SUBORDINATE },
3775         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
3776         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
3777         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
3778         { BER_BVNULL, 0 }
3779 };
3780
3781 static slap_verbmasks datamodes[] = {
3782         { BER_BVC("default"), SYNCDATA_DEFAULT },
3783         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
3784         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
3785         { BER_BVNULL, 0 }
3786 };
3787
3788 static int
3789 parse_syncrepl_retry(
3790         ConfigArgs      *c,
3791         char            *arg,
3792         syncinfo_t      *si )
3793 {
3794         char **retry_list;
3795         int j, k, n;
3796         int use_default = 0;
3797
3798         char *val = arg + STRLENOF( RETRYSTR "=" );
3799         if ( strcasecmp( val, "undefined" ) == 0 ) {
3800                 val = "3600 +";
3801                 use_default = 1;
3802         }
3803
3804         retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
3805         retry_list[0] = NULL;
3806
3807         slap_str2clist( &retry_list, val, " ,\t" );
3808
3809         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3810         n = k / 2;
3811         if ( k % 2 ) {
3812                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3813                         "Error: incomplete syncrepl retry list" );
3814                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3815                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3816                         ch_free( retry_list[k] );
3817                 }
3818                 ch_free( retry_list );
3819                 return 1;
3820         }
3821         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
3822         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
3823         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
3824         for ( j = 0; j < n; j++ ) {
3825                 unsigned long   t;
3826                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3827                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
3828                                 "Error: invalid retry interval \"%s\" (#%d)",
3829                                 retry_list[j*2], j );
3830                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3831                         /* do some cleanup */
3832                         return 1;
3833                 }
3834                 si->si_retryinterval[j] = (time_t)t;
3835                 if ( *retry_list[j*2+1] == '+' ) {
3836                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3837                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3838                         j++;
3839                         break;
3840                 } else {
3841                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3842                                         || si->si_retrynum_init[j] <= 0 )
3843                         {
3844                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3845                                         "Error: invalid initial retry number \"%s\" (#%d)",
3846                                         retry_list[j*2+1], j );
3847                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3848                                 /* do some cleanup */
3849                                 return 1;
3850                         }
3851                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3852                                         || si->si_retrynum[j] <= 0 )
3853                         {
3854                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3855                                         "Error: invalid retry number \"%s\" (#%d)",
3856                                         retry_list[j*2+1], j );
3857                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3858                                 /* do some cleanup */
3859                                 return 1;
3860                         }
3861                 }
3862         }
3863         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3864         si->si_retrynum[j] = RETRYNUM_TAIL;
3865         si->si_retryinterval[j] = 0;
3866         
3867         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3868                 ch_free( retry_list[k] );
3869         }
3870         ch_free( retry_list );
3871         if ( !use_default ) {
3872                 si->si_got |= GOT_RETRY;
3873         }
3874
3875         return 0;
3876 }
3877
3878 static int
3879 parse_syncrepl_line(
3880         ConfigArgs      *c,
3881         syncinfo_t      *si )
3882 {
3883         int     i;
3884         char    *val;
3885
3886         for ( i = 1; i < c->argc; i++ ) {
3887                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
3888                                         STRLENOF( IDSTR "=" ) ) )
3889                 {
3890                         int tmp;
3891                         /* '\0' string terminator accounts for '=' */
3892                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
3893                         if ( lutil_atoi( &tmp, val ) != 0 ) {
3894                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3895                                         "Error: parse_syncrepl_line: "
3896                                         "unable to parse syncrepl id \"%s\"", val );
3897                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3898                                 return -1;
3899                         }
3900                         if ( tmp > SLAP_SYNC_SID_MAX || tmp < 0 ) {
3901                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3902                                         "Error: parse_syncrepl_line: "
3903                                         "syncrepl id %d is out of range [0..4095]", tmp );
3904                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3905                                 return -1;
3906                         }
3907                         si->si_rid = tmp;
3908                         sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
3909                         si->si_got |= GOT_RID;
3910                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
3911                                         STRLENOF( PROVIDERSTR "=" ) ) )
3912                 {
3913                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
3914                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
3915                         si->si_got |= GOT_PROVIDER;
3916                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
3917                                         STRLENOF( SCHEMASTR "=" ) ) )
3918                 {
3919                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
3920                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
3921                                 si->si_schemachecking = 1;
3922                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
3923                                 si->si_schemachecking = 0;
3924                         } else {
3925                                 si->si_schemachecking = 1;
3926                         }
3927                         si->si_got |= GOT_SCHEMACHECKING;
3928                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
3929                                         STRLENOF( FILTERSTR "=" ) ) )
3930                 {
3931                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
3932                         if ( si->si_filterstr.bv_val )
3933                                 ch_free( si->si_filterstr.bv_val );
3934                         ber_str2bv( val, 0, 1, &si->si_filterstr );
3935                         si->si_got |= GOT_FILTER;
3936                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
3937                                         STRLENOF( LOGFILTERSTR "=" ) ) )
3938                 {
3939                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
3940                         if ( si->si_logfilterstr.bv_val )
3941                                 ch_free( si->si_logfilterstr.bv_val );
3942                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
3943                         si->si_got |= GOT_LOGFILTER;
3944                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
3945                                         STRLENOF( SEARCHBASESTR "=" ) ) )
3946                 {
3947                         struct berval   bv;
3948                         int             rc;
3949
3950                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
3951                         if ( si->si_base.bv_val ) {
3952                                 ch_free( si->si_base.bv_val );
3953                         }
3954                         ber_str2bv( val, 0, 0, &bv );
3955                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
3956                         if ( rc != LDAP_SUCCESS ) {
3957                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3958                                         "Invalid base DN \"%s\": %d (%s)",
3959                                         val, rc, ldap_err2string( rc ) );
3960                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3961                                 return -1;
3962                         }
3963                         if ( !be_issubordinate( c->be, &si->si_base ) ) {
3964                                 ch_free( si->si_base.bv_val );
3965                                 BER_BVZERO( &si->si_base );
3966                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3967                                         "Base DN \"%s\" is not within the database naming context",
3968                                         val );
3969                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3970                                 return -1;
3971                         }
3972                         si->si_got |= GOT_SEARCHBASE;
3973                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
3974                                         STRLENOF( LOGBASESTR "=" ) ) )
3975                 {
3976                         struct berval   bv;
3977                         int             rc;
3978
3979                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
3980                         if ( si->si_logbase.bv_val ) {
3981                                 ch_free( si->si_logbase.bv_val );
3982                         }
3983                         ber_str2bv( val, 0, 0, &bv );
3984                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
3985                         if ( rc != LDAP_SUCCESS ) {
3986                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3987                                         "Invalid logbase DN \"%s\": %d (%s)",
3988                                         val, rc, ldap_err2string( rc ) );
3989                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
3990                                 return -1;
3991                         }
3992                         si->si_got |= GOT_LOGBASE;
3993                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
3994                                         STRLENOF( SCOPESTR "=" ) ) )
3995                 {
3996                         int j;
3997                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
3998                         for ( j = 0; !BER_BVISNULL(&scopes[j].key); j++ ) {
3999                                 if (!strcasecmp( val, scopes[j].key.bv_val ) ) {
4000                                         si->si_scope = scopes[j].val;
4001                                         break;
4002                                 }
4003                         }
4004                         if ( BER_BVISNULL(&scopes[j].key) ) {
4005                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4006                                         "Error: parse_syncrepl_line: "
4007                                         "unknown scope \"%s\"", val);
4008                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4009                                 return -1;
4010                         }
4011                         si->si_got |= GOT_SCOPE;
4012                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
4013                                         STRLENOF( ATTRSONLYSTR ) ) )
4014                 {
4015                         si->si_attrsonly = 1;
4016                         si->si_got |= GOT_ATTRSONLY;
4017                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
4018                                         STRLENOF( ATTRSSTR "=" ) ) )
4019                 {
4020                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
4021                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4022                                 char *attr_fname;
4023                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
4024                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
4025                                 if ( si->si_anlist == NULL ) {
4026                                         ch_free( attr_fname );
4027                                         return -1;
4028                                 }
4029                                 si->si_anfile = attr_fname;
4030                         } else {
4031                                 char *str, *s, *next;
4032                                 const char *delimstr = " ,\t";
4033                                 str = ch_strdup( val );
4034                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
4035                                                 s != NULL;
4036                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
4037                                 {
4038                                         if ( strlen(s) == 1 && *s == '*' ) {
4039                                                 si->si_allattrs = 1;
4040                                                 val[ s - str ] = delimstr[0];
4041                                         }
4042                                         if ( strlen(s) == 1 && *s == '+' ) {
4043                                                 si->si_allopattrs = 1;
4044                                                 val [ s - str ] = delimstr[0];
4045                                         }
4046                                 }
4047                                 ch_free( str );
4048                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
4049                                 if ( si->si_anlist == NULL ) {
4050                                         return -1;
4051                                 }
4052                         }
4053                         si->si_got |= GOT_ATTRS;
4054                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
4055                                         STRLENOF( EXATTRSSTR "=" ) ) )
4056                 {
4057                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
4058                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4059                                 char *attr_fname;
4060                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
4061                                 si->si_exanlist = file2anlist(
4062                                         si->si_exanlist, attr_fname, " ,\t" );
4063                                 if ( si->si_exanlist == NULL ) {
4064                                         ch_free( attr_fname );
4065                                         return -1;
4066                                 }
4067                                 ch_free( attr_fname );
4068                         } else {
4069                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
4070                                 if ( si->si_exanlist == NULL ) {
4071                                         return -1;
4072                                 }
4073                         }
4074                         si->si_got |= GOT_EXATTRS;
4075                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
4076                                         STRLENOF( TYPESTR "=" ) ) )
4077                 {
4078                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
4079                         if ( !strncasecmp( val, "refreshOnly",
4080                                                 STRLENOF("refreshOnly") ) )
4081                         {
4082                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4083                         } else if ( !strncasecmp( val, "refreshAndPersist",
4084                                                 STRLENOF("refreshAndPersist") ) )
4085                         {
4086                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
4087                                 si->si_interval = 60;
4088                         } else {
4089                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4090                                         "Error: parse_syncrepl_line: "
4091                                         "unknown sync type \"%s\"", val);
4092                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4093                                 return -1;
4094                         }
4095                         si->si_got |= GOT_TYPE;
4096                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
4097                                         STRLENOF( INTERVALSTR "=" ) ) )
4098                 {
4099                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
4100                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
4101                                 si->si_interval = 0;
4102                         } else if ( strchr( val, ':' ) != NULL ) {
4103                                 char *next, *ptr = val;
4104                                 int dd, hh, mm, ss;
4105
4106                                 dd = strtol( ptr, &next, 10 );
4107                                 if ( next == ptr || next[0] != ':' || dd < 0 ) {
4108                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4109                                                 "Error: parse_syncrepl_line: "
4110                                                 "invalid interval \"%s\", unable to parse days", val );
4111                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4112                                         return -1;
4113                                 }
4114                                 ptr = next + 1;
4115                                 hh = strtol( ptr, &next, 10 );
4116                                 if ( next == ptr || next[0] != ':' || hh < 0 || hh > 24 ) {
4117                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4118                                                 "Error: parse_syncrepl_line: "
4119                                                 "invalid interval \"%s\", unable to parse hours", val );
4120                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4121                                         return -1;
4122                                 }
4123                                 ptr = next + 1;
4124                                 mm = strtol( ptr, &next, 10 );
4125                                 if ( next == ptr || next[0] != ':' || mm < 0 || mm > 60 ) {
4126                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4127                                                 "Error: parse_syncrepl_line: "
4128                                                 "invalid interval \"%s\", unable to parse minutes", val );
4129                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4130                                         return -1;
4131                                 }
4132                                 ptr = next + 1;
4133                                 ss = strtol( ptr, &next, 10 );
4134                                 if ( next == ptr || next[0] != '\0' || ss < 0 || ss > 60 ) {
4135                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4136                                                 "Error: parse_syncrepl_line: "
4137                                                 "invalid interval \"%s\", unable to parse seconds", val );
4138                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4139                                         return -1;
4140                                 }
4141                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
4142                         } else {
4143                                 unsigned long   t;
4144
4145                                 if ( lutil_parse_time( val, &t ) != 0 ) {
4146                                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4147                                                 "Error: parse_syncrepl_line: "
4148                                                 "invalid interval \"%s\"", val );
4149                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4150                                         return -1;
4151                                 }
4152                                 si->si_interval = (time_t)t;
4153                         }
4154                         if ( si->si_interval < 0 ) {
4155                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4156                                         "Error: parse_syncrepl_line: "
4157                                         "invalid interval \"%ld\"",
4158                                         (long) si->si_interval);
4159                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4160                                 return -1;
4161                         }
4162                         si->si_got |= GOT_INTERVAL;
4163                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
4164                                         STRLENOF( RETRYSTR "=" ) ) )
4165                 {
4166                         if ( parse_syncrepl_retry( c, c->argv[ i ], si ) ) {
4167                                 return 1;
4168                         }
4169                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
4170                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
4171                 {
4172                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
4173                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
4174                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
4175                         {
4176                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4177                                         "invalid manageDSAit value \"%s\".\n",
4178                                         val );
4179                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4180                                 return 1;
4181                         }
4182                         si->si_got |= GOT_MANAGEDSAIT;
4183                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
4184                                         STRLENOF( SLIMITSTR "=") ) )
4185                 {
4186                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
4187                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
4188                                 si->si_slimit = 0;
4189
4190                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
4191                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4192                                         "invalid size limit value \"%s\".\n",
4193                                         val );
4194                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4195                                 return 1;
4196                         }
4197                         si->si_got |= GOT_SLIMIT;
4198                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
4199                                         STRLENOF( TLIMITSTR "=" ) ) )
4200                 {
4201                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
4202                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
4203                                 si->si_tlimit = 0;
4204
4205                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
4206                                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4207                                         "invalid time limit value \"%s\".\n",
4208                                         val );
4209                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4210                                 return 1;
4211                         }
4212                         si->si_got |= GOT_TLIMIT;
4213                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
4214                                         STRLENOF( SYNCDATASTR "=" ) ) )
4215                 {
4216                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
4217                         si->si_syncdata = verb_to_mask( val, datamodes );
4218                         si->si_got |= GOT_SYNCDATA;
4219                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
4220                         snprintf( c->cr_msg, sizeof( c->cr_msg ),
4221                                 "Error: parse_syncrepl_line: "
4222                                 "unable to parse \"%s\"\n", c->argv[ i ] );
4223                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4224                         return -1;
4225                 }
4226                 si->si_got |= GOT_BINDCONF;
4227         }
4228
4229         if ( ( si->si_got & GOT_REQUIRED ) != GOT_REQUIRED ) {
4230                 snprintf( c->cr_msg, sizeof( c->cr_msg ),
4231                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
4232                         si->si_got & GOT_RID ? "" : " "IDSTR,
4233                         si->si_got & GOT_PROVIDER ? "" : " "PROVIDERSTR,
4234                         si->si_got & GOT_SEARCHBASE ? "" : " "SEARCHBASESTR );
4235                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4236                 return -1;
4237         }
4238
4239         if ( !( si->si_got & GOT_RETRY ) ) {
4240                 Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": no retry defined, using default\n", 
4241                         si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", 0 );
4242                 if ( si->si_retryinterval == NULL ) {
4243                         if ( parse_syncrepl_retry( c, "retry=undefined", si ) ) {
4244                                 return 1;
4245                         }
4246                 }
4247         }
4248
4249         return 0;
4250 }
4251
4252 static int
4253 add_syncrepl(
4254         ConfigArgs *c )
4255 {
4256         syncinfo_t *si;
4257         int     rc = 0;
4258
4259         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
4260                 snprintf( c->cr_msg, sizeof(c->cr_msg), "database %s does not support "
4261                         "operations required for syncrepl", c->be->be_type );
4262                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
4263                 return 1;
4264         }
4265         if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
4266                 strcpy( c->cr_msg, "rootDN must be defined before syncrepl may be used" );
4267                 Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
4268                 return 1;
4269         }
4270         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
4271
4272         if ( si == NULL ) {
4273                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
4274                 return 1;
4275         }
4276
4277         si->si_bindconf.sb_tls = SB_TLS_OFF;
4278         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
4279         si->si_schemachecking = 0;
4280         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
4281                 &si->si_filterstr );
4282         si->si_base.bv_val = NULL;
4283         si->si_scope = LDAP_SCOPE_SUBTREE;
4284         si->si_attrsonly = 0;
4285         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
4286         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
4287         si->si_attrs = NULL;
4288         si->si_allattrs = 0;
4289         si->si_allopattrs = 0;
4290         si->si_exattrs = NULL;
4291         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4292         si->si_interval = 86400;
4293         si->si_retryinterval = NULL;
4294         si->si_retrynum_init = NULL;
4295         si->si_retrynum = NULL;
4296         si->si_manageDSAit = 0;
4297         si->si_tlimit = 0;
4298         si->si_slimit = 0;
4299
4300         si->si_presentlist = NULL;
4301         LDAP_LIST_INIT( &si->si_nonpresentlist );
4302         ldap_pvt_thread_mutex_init( &si->si_mutex );
4303
4304         rc = parse_syncrepl_line( c, si );
4305
4306         if ( rc == 0 ) {
4307                 /* Must be LDAPv3 because we need controls */
4308                 switch ( si->si_bindconf.sb_version ) {
4309                 case 0:
4310                         /* not explicitly set */
4311                         si->si_bindconf.sb_version = LDAP_VERSION3;
4312                         break;
4313                 case 3:
4314                         /* explicitly set */
4315                         break;
4316                 default:
4317                         Debug( LDAP_DEBUG_ANY,
4318                                 "version %d incompatible with syncrepl\n",
4319                                 si->si_bindconf.sb_version, 0, 0 );
4320                         syncinfo_free( si, 0 ); 
4321                         return 1;
4322                 }
4323
4324                 si->si_be = c->be;
4325                 if ( slapMode & SLAP_SERVER_MODE ) {
4326                         Listener **l = slapd_get_listeners();
4327                         int isMe = 0;
4328
4329                         /* check if URL points to current server. If so, ignore
4330                          * this configuration. We require an exact match. Just
4331                          * in case they really want to do this, they can vary
4332                          * the case of the URL to allow it.
4333                          */
4334                         if ( l && !SLAP_DBHIDDEN( c->be ) ) {
4335                                 int i;
4336                                 for ( i=0; l[i]; i++ ) {
4337                                         if ( bvmatch( &l[i]->sl_url, &si->si_bindconf.sb_uri ) ) {
4338                                                 isMe = 1;
4339                                                 break;
4340                                         }
4341                                 }
4342                         }
4343
4344                         if ( !isMe ) {
4345                                 init_syncrepl( si );
4346                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4347                                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
4348                                         si->si_interval, do_syncrepl, si, "do_syncrepl",
4349                                         si->si_ridtxt );
4350                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4351                                 if ( si->si_re )
4352                                         rc = config_sync_shadow( c ) ? -1 : 0;
4353                                 else
4354                                         rc = -1;
4355                         }
4356                 } else {
4357                         /* mirrormode still needs to see this flag in tool mode */
4358                         rc = config_sync_shadow( c ) ? -1 : 0;
4359                 }
4360         }
4361
4362 #ifdef HAVE_TLS
4363         /* Use main slapd defaults */
4364         bindconf_tls_defaults( &si->si_bindconf );
4365 #endif
4366         if ( rc < 0 ) {
4367                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
4368                 syncinfo_free( si, 0 ); 
4369                 return 1;
4370         } else {
4371                 Debug( LDAP_DEBUG_CONFIG,
4372                         "Config: ** successfully added syncrepl \"%s\"\n",
4373                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
4374                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
4375                 if ( c->be->be_syncinfo ) {
4376                         syncinfo_t *sip;
4377
4378                         si->si_cookieState = c->be->be_syncinfo->si_cookieState;
4379
4380                         // add new syncrepl to end of list (same order as when deleting)
4381                         for ( sip = c->be->be_syncinfo; sip->si_next; sip = sip->si_next );
4382                         sip->si_next = si;
4383                 } else {
4384                         si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
4385                         ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
4386
4387                         c->be->be_syncinfo = si;
4388                 }
4389                 si->si_cookieState->cs_ref++;
4390
4391                 si->si_next = NULL;
4392
4393                 return 0;
4394         }
4395 }
4396
4397 static void
4398 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
4399 {
4400         struct berval bc, uri;
4401         char buf[BUFSIZ*2], *ptr;
4402         ber_len_t len;
4403         int i;
4404 #       define WHATSLEFT        ((ber_len_t) (&buf[sizeof( buf )] - ptr))
4405
4406         BER_BVZERO( bv );
4407
4408         /* temporarily inhibit bindconf from printing URI */
4409         uri = si->si_bindconf.sb_uri;
4410         BER_BVZERO( &si->si_bindconf.sb_uri );
4411         si->si_bindconf.sb_version = 0;
4412         bindconf_unparse( &si->si_bindconf, &bc );
4413         si->si_bindconf.sb_uri = uri;
4414         si->si_bindconf.sb_version = LDAP_VERSION3;
4415
4416         ptr = buf;
4417         assert( si->si_rid >= 0 && si->si_rid <= SLAP_SYNC_SID_MAX );
4418         len = snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
4419                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
4420         if ( len >= sizeof( buf ) ) return;
4421         ptr += len;
4422         if ( !BER_BVISNULL( &bc ) ) {
4423                 if ( WHATSLEFT <= bc.bv_len ) {
4424                         free( bc.bv_val );
4425                         return;
4426                 }
4427                 ptr = lutil_strcopy( ptr, bc.bv_val );
4428                 free( bc.bv_val );
4429         }
4430         if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
4431                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
4432                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
4433                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
4434                 *ptr++ = '"';
4435         }
4436         if ( !BER_BVISNULL( &si->si_base ) ) {
4437                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
4438                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
4439                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
4440                 *ptr++ = '"';
4441         }
4442         if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
4443                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
4444                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
4445                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
4446                 *ptr++ = '"';
4447         }
4448         if ( !BER_BVISNULL( &si->si_logbase ) ) {
4449                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
4450                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
4451                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
4452                 *ptr++ = '"';
4453         }
4454         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
4455                 if ( si->si_scope == scopes[i].val ) {
4456                         if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + scopes[i].key.bv_len ) return;
4457                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
4458                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
4459                         break;
4460                 }
4461         }
4462         if ( si->si_attrsonly ) {
4463                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
4464                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
4465         }
4466         if ( si->si_anfile ) {
4467                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
4468                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
4469                 ptr = lutil_strcopy( ptr, si->si_anfile );
4470                 *ptr++ = '"';
4471         } else if ( si->si_allattrs || si->si_allopattrs ||
4472                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
4473         {
4474                 char *old;
4475
4476                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
4477                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
4478                 old = ptr;
4479                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
4480                 if ( ptr == NULL ) return;
4481                 if ( si->si_allattrs ) {
4482                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
4483                         if ( old != ptr ) *ptr++ = ',';
4484                         *ptr++ = '*';
4485                 }
4486                 if ( si->si_allopattrs ) {
4487                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
4488                         if ( old != ptr ) *ptr++ = ',';
4489                         *ptr++ = '+';
4490                 }
4491                 *ptr++ = '"';
4492         }
4493         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
4494                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
4495                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
4496                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
4497                 if ( ptr == NULL ) return;
4498         }
4499         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
4500         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
4501         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
4502         
4503         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
4504         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
4505         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
4506                 "refreshAndPersist" : "refreshOnly" );
4507
4508         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
4509                 int dd, hh, mm, ss;
4510
4511                 dd = si->si_interval;
4512                 ss = dd % 60;
4513                 dd /= 60;
4514                 mm = dd % 60;
4515                 dd /= 60;
4516                 hh = dd % 24;
4517                 dd /= 24;
4518                 len = snprintf( ptr, WHATSLEFT, " %s=%02d:%02d:%02d:%02d",
4519                         INTERVALSTR, dd, hh, mm, ss );
4520                 if ( len >= WHATSLEFT ) return;
4521                 ptr += len;
4522         }
4523
4524         if ( si->si_got & GOT_RETRY ) {
4525                 const char *space = "";
4526                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
4527                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
4528                 for (i=0; si->si_retryinterval[i]; i++) {
4529                         len = snprintf( ptr, WHATSLEFT, "%s%ld ", space,
4530                                 (long) si->si_retryinterval[i] );
4531                         space = " ";
4532                         if ( WHATSLEFT - 1 <= len ) return;
4533                         ptr += len;
4534                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
4535                                 *ptr++ = '+';
4536                         else {
4537                                 len = snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
4538                                 if ( WHATSLEFT <= len ) return;
4539                                 ptr += len;
4540                         }
4541                 }
4542                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
4543                 *ptr++ = '"';
4544         } else {
4545                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=undefined" );
4546         }
4547
4548         if ( si->si_slimit ) {
4549                 len = snprintf( ptr, WHATSLEFT, " " SLIMITSTR "=%d", si->si_slimit );
4550                 if ( WHATSLEFT <= len ) return;
4551                 ptr += len;
4552         }
4553
4554         if ( si->si_tlimit ) {
4555                 len = snprintf( ptr, WHATSLEFT, " " TLIMITSTR "=%d", si->si_tlimit );
4556                 if ( WHATSLEFT <= len ) return;
4557                 ptr += len;
4558         }
4559
4560         if ( si->si_syncdata ) {
4561                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
4562                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
4563                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
4564                         ptr = lutil_strcopy( ptr, bc.bv_val );
4565                 }
4566         }
4567         bc.bv_len = ptr - buf;
4568         bc.bv_val = buf;
4569         ber_dupbv( bv, &bc );
4570 }
4571
4572 int
4573 syncrepl_config( ConfigArgs *c )
4574 {
4575         if (c->op == SLAP_CONFIG_EMIT) {
4576                 if ( c->be->be_syncinfo ) {
4577                         struct berval bv;
4578                         syncinfo_t *si;
4579
4580                         for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
4581                                 syncrepl_unparse( si, &bv ); 
4582                                 ber_bvarray_add( &c->rvalue_vals, &bv );
4583                         }
4584                         return 0;
4585                 }
4586                 return 1;
4587         } else if ( c->op == LDAP_MOD_DELETE ) {
4588                 int isrunning = 0;
4589                 if ( c->be->be_syncinfo ) {
4590                         syncinfo_t *si, **sip;
4591                         int i;
4592
4593                         for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
4594                                 si = *sip;
4595                                 if ( c->valx == -1 || i == c->valx ) {
4596                                         *sip = si->si_next;
4597                                         /* If the task is currently active, we have to leave
4598                                          * it running. It will exit on its own. This will only
4599                                          * happen when running on the cn=config DB.
4600                                          */
4601                                         if ( si->si_re ) {
4602                                                 if ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
4603                                                         isrunning = 1;
4604                                                 } else {
4605                                                         if ( si->si_conn ) {
4606                                                                 isrunning = 1;
4607                                                                 /* If there's a persistent connection, we don't
4608                                                                  * know if it's already got a thread queued.
4609                                                                  * so defer the free, but reschedule the task.
4610                                                                  * If there's a connection thread queued, it
4611                                                                  * will cleanup as necessary. If not, then the
4612                                                                  * runqueue task will cleanup.
4613                                                                  */
4614                                                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4615                                                                 if ( !ldap_pvt_runqueue_isrunning( &slapd_rq, si->si_re )) {
4616                                                                         si->si_re->interval.tv_sec = 0;
4617                                                                         ldap_pvt_runqueue_resched( &slapd_rq, si->si_re, 0 );
4618                                                                         si->si_re->interval.tv_sec = si->si_interval;
4619                                                                 }
4620                                                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4621                                                         }
4622                                                         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
4623                                                 }
4624                                         }
4625                                         if ( isrunning ) {
4626                                                 si->si_ctype = 0;
4627                                                 si->si_next = NULL;
4628                                         } else {
4629                                                 syncinfo_free( si, 0 );
4630                                         }
4631                                         if ( i == c->valx )
4632                                                 break;
4633                                 } else {
4634                                         sip = &si->si_next;
4635                                 }
4636                         }
4637                 }
4638                 if ( !c->be->be_syncinfo ) {
4639                         SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_SHADOW_MASK;
4640                 }
4641                 return 0;
4642         }
4643         if ( SLAP_SLURP_SHADOW( c->be ) ) {
4644                 Debug(LDAP_DEBUG_ANY, "%s: "
4645                         "syncrepl: database already shadowed.\n",
4646                         c->log, 0, 0);
4647                 return(1);
4648         } else {
4649                 return add_syncrepl( c );
4650         }
4651 }