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