]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
2fd3d59f594084b0e1d2a494d04d859ae75b5457
[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         slap_bindconf           si_bindconf;
52         struct berval           si_base;
53         struct berval           si_logbase;
54         struct berval           si_filterstr;
55         struct berval           si_logfilterstr;
56         int                                     si_scope;
57         int                                     si_attrsonly;
58         char                            *si_anfile;
59         AttributeName           *si_anlist;
60         AttributeName           *si_exanlist;
61         char                            **si_attrs;
62         char                            **si_exattrs;
63         int                                     si_allattrs;
64         int                                     si_allopattrs;
65         int                                     si_schemachecking;
66         int                                     si_type;        /* the active type */
67         int                                     si_ctype;       /* the configured type */
68         time_t                          si_interval;
69         time_t                          *si_retryinterval;
70         int                                     *si_retrynum_init;
71         int                                     *si_retrynum;
72         struct sync_cookie      si_syncCookie;
73         int                                     si_manageDSAit;
74         int                                     si_slimit;
75         int                                     si_tlimit;
76         int                                     si_refreshDelete;
77         int                                     si_refreshPresent;
78         int                                     si_syncdata;
79         int                                     si_logstate;
80         int                                     si_conn_setup;
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_SUBTREE;
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_bindconf.sb_uri.bv_val );
423         if ( rc != LDAP_SUCCESS ) {
424                 Debug( LDAP_DEBUG_ANY,
425                         "do_syncrep1: ldap_initialize failed (%s)\n",
426                         si->si_bindconf.sb_uri.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_bindconf.sb_uri.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                 Debug( LDAP_DEBUG_SYNC, "not compiled with SASL support\n", 0, 0, 0 );
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                                  * (happens with back-sql...) */
695                                 if ( BER_BVISEMPTY( &syncUUID ) ) {
696                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: "
697                                                 "got empty syncUUID\n", 0, 0, 0 );
698                                         rc = -1;
699                                         goto done;
700                                 }
701                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
702                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
703                                         if ( !BER_BVISNULL( &cookie ) ) {
704                                                 ch_free( syncCookie.octet_str.bv_val );
705                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
706                                         }
707                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
708                                         {
709                                                 slap_parse_sync_cookie( &syncCookie, NULL );
710                                         }
711                                 }
712                                 if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
713                                         entry = NULL;
714                                         modlist = NULL;
715                                         if ( syncrepl_message_to_op( si, op, msg ) == LDAP_SUCCESS &&
716                                                 !BER_BVISNULL( &syncCookie.ctxcsn ) ) {
717                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
718                                         }
719                                 } else if ( syncrepl_message_to_entry( si, op, msg,
720                                         &modlist, &entry, syncstate ) == LDAP_SUCCESS ) {
721                                         rc_efree = syncrepl_entry( si, op, entry, &modlist,
722                                                 syncstate, &syncUUID, &syncCookie_req, &syncCookie.ctxcsn );
723                                         if ( !BER_BVISNULL( &syncCookie.ctxcsn ) )
724                                         {
725                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
726                                         }
727                                 }
728                                 ldap_controls_free( rctrls );
729                                 if ( modlist ) {
730                                         slap_mods_free( modlist, 1 );
731                                 }
732                                 if ( rc_efree && entry ) {
733                                         entry_free( entry );
734                                 }
735                                 entry = NULL;
736                                 break;
737
738                         case LDAP_RES_SEARCH_REFERENCE:
739                                 Debug( LDAP_DEBUG_ANY,
740                                         "do_syncrep2: reference received error\n", 0, 0, 0 );
741                                 break;
742
743                         case LDAP_RES_SEARCH_RESULT:
744                                 Debug( LDAP_DEBUG_SYNC,
745                                         "do_syncrep2: LDAP_RES_SEARCH_RESULT\n", 0, 0, 0 );
746                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
747                                         &rctrls, 0 );
748 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
749                                 if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
750                                         /* map old result code to registered code */
751                                         err = LDAP_SYNC_REFRESH_REQUIRED;
752                                 }
753 #endif
754                                 if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
755                                         if ( si->si_logstate == SYNCLOG_LOGGING ) {
756                                                 si->si_logstate = SYNCLOG_FALLBACK;
757                                         }
758                                         rc = err;
759                                         goto done;
760                                 }
761                                 if ( rctrls ) {
762                                         rctrlp = *rctrls;
763                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
764
765                                         ber_scanf( ber, "{" /*"}"*/);
766                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
767                                                 ber_scanf( ber, "m", &cookie );
768                                                 if ( !BER_BVISNULL( &cookie ) ) {
769                                                         ch_free( syncCookie.octet_str.bv_val );
770                                                         ber_dupbv( &syncCookie.octet_str, &cookie);
771                                                 }
772                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
773                                                 {
774                                                         slap_parse_sync_cookie( &syncCookie, NULL );
775                                                 }
776                                         }
777                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
778                                         {
779                                                 ber_scanf( ber, "b", &refreshDeletes );
780                                         }
781                                         ber_scanf( ber, /*"{"*/ "}" );
782                                 }
783                                 if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
784                                         match = -1;
785                                 } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
786                                         match = 1;
787                                 } else {
788                                         value_match( &match, slap_schema.si_ad_entryCSN,
789                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
790                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
791                                                 &syncCookie_req.ctxcsn, &syncCookie.ctxcsn,
792                                                 &text );
793                                 }
794                                 if ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
795                                         match < 0 && err == LDAP_SUCCESS )
796                                 {
797                                         syncrepl_updateCookie( si, op, psub, &syncCookie );
798                                 }
799                                 if ( rctrls ) {
800                                         ldap_controls_free( rctrls );
801                                 }
802                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
803                                         /* FIXME : different error behaviors according to
804                                          *      1) err code : LDAP_BUSY ...
805                                          *      2) on err policy : stop service, stop sync, retry
806                                          */
807                                         if ( refreshDeletes == 0 && match < 0 &&
808                                                 err == LDAP_SUCCESS )
809                                         {
810                                                 syncrepl_del_nonpresent( op, si, NULL );
811                                         } else {
812                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
813                                                 si->si_presentlist = NULL;
814                                         }
815                                 }
816                                 if ( err == LDAP_SUCCESS
817                                         && si->si_logstate == SYNCLOG_FALLBACK ) {
818                                         si->si_logstate = SYNCLOG_LOGGING;
819                                         rc = LDAP_SYNC_REFRESH_REQUIRED;
820                                 } else {
821                                         rc = -2;
822                                 }
823                                 goto done;
824                                 break;
825
826                         case LDAP_RES_INTERMEDIATE:
827                                 rc = ldap_parse_intermediate( si->si_ld, msg,
828                                         &retoid, &retdata, NULL, 0 );
829                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
830                                         ber_init2( ber, retdata, LBER_USE_DER );
831
832                                         switch ( si_tag = ber_peek_tag( ber, &len )) {
833                                         ber_tag_t tag;
834                                         case LDAP_TAG_SYNC_NEW_COOKIE:
835                                                 Debug( LDAP_DEBUG_SYNC,
836                                                         "do_syncrep2: %s - %s%s\n", 
837                                                         "LDAP_RES_INTERMEDIATE", 
838                                                         "NEW_COOKIE", "\n" );
839                                                 ber_scanf( ber, "tm", &tag, &cookie );
840                                                 break;
841                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
842                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
843                                                 Debug( LDAP_DEBUG_SYNC,
844                                                         "do_syncrep2: %s - %s%s\n", 
845                                                         "LDAP_RES_INTERMEDIATE", 
846                                                         si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
847                                                         "REFRESH_PRESENT" : "REFRESH_DELETE",
848                                                         "\n" );
849                                                 if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
850                                                         si->si_refreshDelete = 1;
851                                                 } else {
852                                                         si->si_refreshPresent = 1;
853                                                 }
854                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
855                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
856                                                 {
857                                                         ber_scanf( ber, "m", &cookie );
858                                                         if ( !BER_BVISNULL( &cookie ) ) {
859                                                                 ch_free( syncCookie.octet_str.bv_val );
860                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
861                                                         }
862                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
863                                                         {
864                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
865                                                         }
866                                                 }
867                                                 if ( ber_peek_tag( ber, &len ) ==
868                                                         LDAP_TAG_REFRESHDONE )
869                                                 {
870                                                         ber_scanf( ber, "b", &refreshDone );
871                                                 }
872                                                 ber_scanf( ber, /*"{"*/ "}" );
873                                                 break;
874                                         case LDAP_TAG_SYNC_ID_SET:
875                                                 Debug( LDAP_DEBUG_SYNC,
876                                                         "do_syncrep2: %s - %s%s\n", 
877                                                         "LDAP_RES_INTERMEDIATE", 
878                                                         "SYNC_ID_SET",
879                                                         "\n" );
880                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
881                                                 if ( ber_peek_tag( ber, &len ) ==
882                                                         LDAP_TAG_SYNC_COOKIE )
883                                                 {
884                                                         ber_scanf( ber, "m", &cookie );
885                                                         if ( !BER_BVISNULL( &cookie ) ) {
886                                                                 ch_free( syncCookie.octet_str.bv_val );
887                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
888                                                         }
889                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
890                                                         {
891                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
892                                                         }
893                                                 }
894                                                 if ( ber_peek_tag( ber, &len ) ==
895                                                         LDAP_TAG_REFRESHDELETES )
896                                                 {
897                                                         ber_scanf( ber, "b", &refreshDeletes );
898                                                 }
899                                                 ber_scanf( ber, "[W]", &syncUUIDs );
900                                                 ber_scanf( ber, /*"{"*/ "}" );
901                                                 if ( refreshDeletes ) {
902                                                         syncrepl_del_nonpresent( op, si, syncUUIDs );
903                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
904                                                 } else {
905                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
906                                                                 struct berval *syncuuid_bv;
907                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
908                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
909                                                                 avl_insert( &si->si_presentlist,
910                                                                         (caddr_t) syncuuid_bv,
911                                                                         syncuuid_cmp, avl_dup_error );
912                                                         }
913                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
914                                                 }
915                                                 break;
916                                         default:
917                                                 Debug( LDAP_DEBUG_ANY,
918                                                         "do_syncrep2 : unknown syncinfo tag (%ld)\n",
919                                                 (long) si_tag, 0, 0 );
920                                                 ldap_memfree( retoid );
921                                                 ber_bvfree( retdata );
922                                                 continue;
923                                         }
924
925                                         if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
926                                                 match = -1;
927                                         } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
928                                                 match = 1;
929                                         } else {
930                                                 value_match( &match, slap_schema.si_ad_entryCSN,
931                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
932                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
933                                                         &syncCookie_req.ctxcsn,
934                                                         &syncCookie.ctxcsn, &text );
935                                         }
936
937                                         if ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
938                                                 match < 0 )
939                                         {
940                                                 syncrepl_updateCookie( si, op, psub, &syncCookie);
941                                         }
942
943                                         if ( si->si_refreshPresent == 1 ) {
944                                                 if ( match < 0 ) {
945                                                         syncrepl_del_nonpresent( op, si, NULL );
946                                                 }
947                                         } 
948
949                                         ldap_memfree( retoid );
950                                         ber_bvfree( retdata );
951                                         break;
952
953                                 } else {
954                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
955                                                 "unknown intermediate response (%d)\n",
956                                                 rc, 0, 0 );
957                                         ldap_memfree( retoid );
958                                         ber_bvfree( retdata );
959                                         break;
960                                 }
961                                 break;
962
963                         default:
964                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
965                                         "unknown message\n", 0, 0, 0 );
966                                 break;
967
968                         }
969                         if ( !BER_BVISNULL( &syncCookie.octet_str )) {
970                                 slap_sync_cookie_free( &syncCookie_req, 0 );
971                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
972                                 slap_sync_cookie_free( &syncCookie, 0 );
973                         }
974                 }
975                 ldap_msgfree( res );
976                 res = NULL;
977         }
978
979         if ( rc == -1 ) {
980                 const char *errstr;
981
982                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
983                 errstr = ldap_err2string( rc );
984                 
985                 Debug( LDAP_DEBUG_ANY,
986                         "do_syncrep2 : %s\n", errstr, 0, 0 );
987         }
988
989 done:
990         slap_sync_cookie_free( &syncCookie, 0 );
991         slap_sync_cookie_free( &syncCookie_req, 0 );
992
993         if ( res ) ldap_msgfree( res );
994
995         if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
996                 if ( si->si_conn_setup ) {
997                         ber_socket_t s;
998                         ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
999                         connection_client_stop( s );
1000                         si->si_conn_setup = 0;
1001                 }
1002                 ldap_unbind_ext( si->si_ld, NULL, NULL );
1003                 si->si_ld = NULL;
1004         }
1005
1006         return rc;
1007 }
1008
1009 static void *
1010 do_syncrepl(
1011         void    *ctx,
1012         void    *arg )
1013 {
1014         struct re_s* rtask = arg;
1015         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1016         Connection conn = {0};
1017         OperationBuffer opbuf;
1018         Operation *op;
1019         int rc = LDAP_SUCCESS;
1020         int dostop = 0;
1021         ber_socket_t s;
1022         int i, defer = 1;
1023         Backend *be;
1024
1025         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
1026
1027         if ( si == NULL )
1028                 return NULL;
1029
1030         ldap_pvt_thread_mutex_lock( &si->si_mutex );
1031
1032         switch( abs( si->si_type )) {
1033         case LDAP_SYNC_REFRESH_ONLY:
1034         case LDAP_SYNC_REFRESH_AND_PERSIST:
1035                 break;
1036         default:
1037                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1038                 return NULL;
1039         }
1040
1041         if ( slapd_shutdown ) {
1042                 if ( si->si_ld ) {
1043                         if ( si->si_conn_setup ) {
1044                                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1045                                 connection_client_stop( s );
1046                                 si->si_conn_setup = 0;
1047                         }
1048                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1049                         si->si_ld = NULL;
1050                 }
1051                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1052                 return NULL;
1053         }
1054
1055         op = (Operation *) &opbuf;
1056         connection_fake_init( &conn, op, ctx );
1057
1058         /* use global malloc for now */
1059         op->o_tmpmemctx = NULL;
1060         op->o_tmpmfuncs = &ch_mfuncs;
1061
1062         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1063         op->o_bd = be = si->si_be;
1064         op->o_dn = op->o_bd->be_rootdn;
1065         op->o_ndn = op->o_bd->be_rootndn;
1066
1067         /* Establish session, do search */
1068         if ( !si->si_ld ) {
1069                 si->si_refreshDelete = 0;
1070                 si->si_refreshPresent = 0;
1071                 rc = do_syncrep1( op, si );
1072         }
1073
1074 reload:
1075         /* Process results */
1076         if ( rc == LDAP_SUCCESS ) {
1077                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1078
1079                 rc = do_syncrep2( op, si );
1080                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1081                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1082                         goto reload;
1083                 }
1084
1085                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1086                         /* If we succeeded, enable the connection for further listening.
1087                          * If we failed, tear down the connection and reschedule.
1088                          */
1089                         if ( rc == LDAP_SUCCESS ) {
1090                                 if ( si->si_conn_setup ) {
1091                                         connection_client_enable( s );
1092                                 } else {
1093                                         rc = connection_client_setup( s, do_syncrepl, arg );
1094                                         if ( rc == 0 )
1095                                                 si->si_conn_setup = 1;
1096                                 } 
1097                         } else if ( si->si_conn_setup ) {
1098                                 dostop = 1;
1099                         }
1100                 } else {
1101                         if ( rc == -2 ) rc = 0;
1102                 }
1103         }
1104
1105         /* At this point, we have 4 cases:
1106          * 1) for any hard failure, give up and remove this task
1107          * 2) for ServerDown, reschedule this task to run
1108          * 3) for Refresh and Success, reschedule to run
1109          * 4) for Persist and Success, reschedule to defer
1110          */
1111         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1112
1113         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1114                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1115         }
1116
1117         if ( dostop ) {
1118                 connection_client_stop( s );
1119         }
1120
1121         if ( rc == LDAP_SUCCESS ) {
1122                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1123                         defer = 0;
1124                 }
1125                 rtask->interval.tv_sec = si->si_interval;
1126                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1127                 if ( si->si_retrynum ) {
1128                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
1129                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1130                         }
1131                         si->si_retrynum[i] = -2;
1132                 }
1133         } else {
1134                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1135                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
1136                                 break;
1137                 }
1138
1139                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
1140                         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1141                 } else if ( si->si_retrynum[i] >= -1 ) {
1142                         if ( si->si_retrynum[i] > 0 )
1143                                 si->si_retrynum[i]--;
1144                         rtask->interval.tv_sec = si->si_retryinterval[i];
1145                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1146                         slap_wake_listener();
1147                 }
1148         }
1149         
1150         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1151         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1152
1153         return NULL;
1154 }
1155
1156 static slap_verbmasks modops[] = {
1157         { BER_BVC("add"), LDAP_REQ_ADD },
1158         { BER_BVC("delete"), LDAP_REQ_DELETE },
1159         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1160         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1161         { BER_BVNULL, 0 }
1162 };
1163
1164 static Modifications *
1165 syncrepl_accesslog_mods(
1166         syncinfo_t *si,
1167         struct berval *vals
1168 )
1169 {
1170         char *colon;
1171         const char *text;
1172         AttributeDescription *ad;
1173         struct berval bv, bv2;
1174         short op;
1175         Modifications *mod = NULL, *modlist = NULL, **modtail;
1176         int i;
1177
1178         modtail = &modlist;
1179
1180         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1181                 ad = NULL;
1182                 bv = vals[i];
1183
1184                 colon = ber_bvchr( &bv, ':' );
1185                 if ( !colon )
1186                         continue;       /* invalid */
1187                 bv.bv_len = colon - bv.bv_val;
1188                 if ( slap_bv2ad( &bv, &ad, &text )) {
1189                         /* Invalid */
1190                         continue;
1191                 }
1192                 /* Ignore dynamically generated attrs */
1193                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC )
1194                         continue;
1195                 /* Ignore excluded attrs */
1196                 if ( ldap_charray_inlist( si->si_exattrs,
1197                         ad->ad_type->sat_cname.bv_val ))
1198                         continue;
1199
1200                 switch(colon[1]) {
1201                 case '+':       op = LDAP_MOD_ADD; break;
1202                 case '-':       op = LDAP_MOD_DELETE; break;
1203                 case '=':       op = LDAP_MOD_REPLACE; break;
1204                 case '#':       op = LDAP_MOD_INCREMENT; break;
1205                 default:        continue;
1206                 }
1207
1208                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1209                         mod = (Modifications *) ch_malloc( sizeof( Modifications ));
1210                         mod->sml_flags = 0;
1211                         mod->sml_op = op;
1212                         mod->sml_next = NULL;
1213                         mod->sml_desc = ad;
1214                         mod->sml_type = ad->ad_cname;
1215                         mod->sml_values = NULL;
1216                         mod->sml_nvalues = NULL;
1217
1218                         *modtail = mod;
1219                         modtail = &mod->sml_next;
1220                 }
1221                 if ( colon[2] == ' ' ) {
1222                         bv.bv_val = colon + 3;
1223                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1224                         ber_dupbv( &bv2, &bv );
1225                         ber_bvarray_add( &mod->sml_values, &bv2 );
1226                 }
1227         }
1228         return modlist;
1229 }
1230
1231 static Modifications *
1232 syncrepl_changelog_mods(
1233         syncinfo_t *si,
1234         struct berval *vals
1235 )
1236 {
1237         return NULL;    /* FIXME */
1238 }
1239
1240 static int
1241 syncrepl_message_to_op(
1242         syncinfo_t      *si,
1243         Operation       *op,
1244         LDAPMessage     *msg
1245 )
1246 {
1247         BerElement      *ber = NULL;
1248         Modifications   *modlist = NULL;
1249         logschema *ls;
1250         SlapReply rs = { REP_RESULT };
1251         slap_callback cb = { NULL, null_callback, NULL, NULL };
1252
1253         const char      *text;
1254         char txtbuf[SLAP_TEXT_BUFLEN];
1255         size_t textlen = sizeof txtbuf;
1256
1257         struct berval   bdn, dn = BER_BVNULL, ndn;
1258         struct berval   bv, *bvals = NULL;
1259         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1260                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1261                 psup = BER_BVNULL, nsup = BER_BVNULL;
1262         int             rc, deleteOldRdn = 0;
1263
1264         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1265                 Debug( LDAP_DEBUG_ANY,
1266                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1267                 return -1;
1268         }
1269
1270         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1271                 ls = &accesslog_sc;
1272         else
1273                 ls = &changelog_sc;
1274
1275         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1276
1277         if ( rc != LDAP_SUCCESS ) {
1278                 Debug( LDAP_DEBUG_ANY,
1279                         "syncrepl_message_to_op : dn get failed (%d)", rc, 0, 0 );
1280                 return rc;
1281         }
1282
1283         op->o_tag = LBER_DEFAULT;
1284
1285         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ))
1286                 == LDAP_SUCCESS ) {
1287                 if ( bv.bv_val == NULL )
1288                         break;
1289
1290                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn )) {
1291                         bdn = bvals[0];
1292                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1293                         ber_dupbv( &op->o_req_dn, &dn );
1294                         ber_dupbv( &op->o_req_ndn, &ndn );
1295                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1296                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1297                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req )) {
1298                         int i = verb_to_mask( bvals[0].bv_val, modops );
1299                         if ( i < 0 ) {
1300                                 Debug( LDAP_DEBUG_ANY,
1301                                         "syncrepl_message_to_op : unknown op %s",
1302                                         bvals[0].bv_val, 0, 0 );
1303                                 ch_free( bvals );
1304                                 rc = -1;
1305                                 goto done;
1306                         }
1307                         op->o_tag = modops[i].mask;
1308                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod )) {
1309                         /* Parse attribute into modlist */
1310                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1311                                 modlist = syncrepl_accesslog_mods( si, bvals );
1312                         else
1313                                 modlist = syncrepl_changelog_mods( si, bvals );
1314                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn )) {
1315                         rdn = bvals[0];
1316                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn )) {
1317                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ))
1318                                 deleteOldRdn = 1;
1319                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup )) {
1320                         sup = bvals[0];
1321                 } else if ( !ber_bvstrcasecmp( &bv,
1322                         &slap_schema.si_ad_entryCSN->ad_cname )) {
1323                         slap_queue_csn( op, bvals );
1324                 }
1325                 ch_free( bvals );
1326         }
1327
1328         /* If we didn't get a mod type or a target DN, bail out */
1329         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn )) {
1330                 rc = -1;
1331                 goto done;
1332         }
1333
1334         op->o_callback = &cb;
1335
1336         switch( op->o_tag ) {
1337         case LDAP_REQ_ADD:
1338         case LDAP_REQ_MODIFY:
1339                 /* If we didn't get required data, bail */
1340                 if ( !modlist ) goto done;
1341
1342                 rc = slap_mods_check( modlist, &text, txtbuf, textlen, NULL );
1343
1344                 if ( rc != LDAP_SUCCESS ) {
1345                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: mods check (%s)\n",
1346                                 text, 0, 0 );
1347                         goto done;
1348                 }
1349
1350                 if ( op->o_tag == LDAP_REQ_ADD ) {
1351                         op->ora_e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1352                         op->ora_e->e_name = op->o_req_dn;
1353                         op->ora_e->e_nname = op->o_req_ndn;
1354                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1355                         if( rc != LDAP_SUCCESS ) {
1356                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: mods2entry (%s)\n",
1357                                         text, 0, 0 );
1358                         } else {
1359                                 rc = op->o_bd->be_add( op, &rs );
1360                         }
1361                         be_entry_release_w( op, op->ora_e );
1362                 } else {
1363                         op->orm_modlist = modlist;
1364                         rc = op->o_bd->be_modify( op, &rs );
1365                 }
1366                 break;
1367         case LDAP_REQ_MODRDN:
1368                 if ( BER_BVISNULL( &rdn )) goto done;
1369
1370                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ))
1371                         goto done;
1372                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ))
1373                         goto done;
1374                 if ( !BER_BVISNULL( &sup )) {
1375                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ))
1376                                 goto done;
1377                         op->orr_newSup = &psup;
1378                         op->orr_nnewSup = &nsup;
1379                 }
1380                 op->orr_newrdn = prdn;
1381                 op->orr_nnewrdn = nrdn;
1382                 op->orr_deleteoldrdn = deleteOldRdn;
1383                 rc = op->o_bd->be_modrdn( op, &rs );
1384                 break;
1385         case LDAP_REQ_DELETE:
1386                 rc = op->o_bd->be_delete( op, &rs );
1387                 break;
1388         }
1389 done:
1390         slap_graduate_commit_csn( op );
1391         if ( modlist )
1392                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1393         if ( !BER_BVISNULL( &rdn )) {
1394                 if ( !BER_BVISNULL( &nsup ))
1395                         ch_free( nsup.bv_val );
1396                 if ( !BER_BVISNULL( &psup ))
1397                         ch_free( psup.bv_val );
1398                 if ( !BER_BVISNULL( &nrdn ))
1399                         ch_free( nrdn.bv_val );
1400                 if ( !BER_BVISNULL( &prdn ))
1401                         ch_free( prdn.bv_val );
1402         }
1403         ber_free ( ber, 0 );
1404         return rc;
1405 }
1406
1407 static int
1408 syncrepl_message_to_entry(
1409         syncinfo_t      *si,
1410         Operation       *op,
1411         LDAPMessage     *msg,
1412         Modifications   **modlist,
1413         Entry                   **entry,
1414         int             syncstate
1415 )
1416 {
1417         Entry           *e = NULL;
1418         BerElement      *ber = NULL;
1419         Modifications   tmp;
1420         Modifications   *mod;
1421         Modifications   **modtail = modlist;
1422
1423         const char      *text;
1424         char txtbuf[SLAP_TEXT_BUFLEN];
1425         size_t textlen = sizeof txtbuf;
1426
1427         struct berval   bdn = {0, NULL}, dn, ndn;
1428         int             rc;
1429
1430         *modlist = NULL;
1431
1432         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1433                 Debug( LDAP_DEBUG_ANY,
1434                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1435                 return -1;
1436         }
1437
1438         op->o_tag = LDAP_REQ_ADD;
1439
1440         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1441
1442         if ( rc != LDAP_SUCCESS ) {
1443                 Debug( LDAP_DEBUG_ANY,
1444                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1445                 return rc;
1446         }
1447
1448         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1449         ber_dupbv( &op->o_req_dn, &dn );
1450         ber_dupbv( &op->o_req_ndn, &ndn );
1451         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1452         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1453
1454         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1455                 if ( entry )
1456                         *entry = NULL;
1457                 return LDAP_SUCCESS;
1458         }
1459
1460         if ( entry == NULL ) {
1461                 return -1;
1462         }
1463
1464         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1465         *entry = e;
1466         e->e_name = op->o_req_dn;
1467         e->e_nname = op->o_req_ndn;
1468
1469         while ( ber_remaining( ber ) ) {
1470                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1471                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1472                 {
1473                         break;
1474                 }
1475
1476                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1477
1478                 mod->sml_op = LDAP_MOD_REPLACE;
1479                 mod->sml_flags = 0;
1480                 mod->sml_next = NULL;
1481                 mod->sml_desc = NULL;
1482                 mod->sml_type = tmp.sml_type;
1483                 mod->sml_values = tmp.sml_values;
1484                 mod->sml_nvalues = NULL;
1485
1486                 *modtail = mod;
1487                 modtail = &mod->sml_next;
1488         }
1489
1490         if ( *modlist == NULL ) {
1491                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1492                         0, 0, 0 );
1493                 rc = -1;
1494                 goto done;
1495         }
1496
1497         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1498
1499         if ( rc != LDAP_SUCCESS ) {
1500                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1501                         text, 0, 0 );
1502                 goto done;
1503         }
1504
1505         /* Strip out dynamically generated attrs */
1506         for ( modtail = modlist; *modtail ; ) {
1507                 mod = *modtail;
1508                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
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         /* Strip out attrs in exattrs list */
1518         for ( modtail = modlist; *modtail ; ) {
1519                 mod = *modtail;
1520                 if ( ldap_charray_inlist( si->si_exattrs,
1521                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1522                         *modtail = mod->sml_next;
1523                         slap_mod_free( &mod->sml_mod, 0 );
1524                         ch_free( mod );
1525                 } else {
1526                         modtail = &mod->sml_next;
1527                 }
1528         }
1529         
1530         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1531         if( rc != LDAP_SUCCESS ) {
1532                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1533                         text, 0, 0 );
1534         }
1535
1536 done:
1537         ber_free ( ber, 0 );
1538         if ( rc != LDAP_SUCCESS ) {
1539                 if ( e ) {
1540                         entry_free( e );
1541                         *entry = e = NULL;
1542                 }
1543         }
1544
1545         return rc;
1546 }
1547
1548 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1549
1550 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1551  * entry if a previous refresh was interrupted before sending us a new
1552  * context state. We try to compare the new entry to the existing entry
1553  * and ignore the new entry if they are the same.
1554  *
1555  * Also, we may get an update where the entryDN has changed, due to
1556  * a ModDn on the provider. We detect this as well, so we can issue
1557  * the corresponding operation locally.
1558  *
1559  * In the case of a modify, we get a list of all the attributes
1560  * in the original entry. Rather than deleting the entry and re-adding it,
1561  * we issue a Modify request that deletes all the attributes and adds all
1562  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1563  * entry.
1564  *
1565  * We don't try to otherwise distinguish ModDN from Modify; in the case of
1566  * a ModDN we will issue both operations on the local database.
1567  */
1568 typedef struct dninfo {
1569         Entry *new_entry;
1570         struct berval dn;
1571         struct berval ndn;
1572         int renamed;    /* Was an existing entry renamed? */
1573         int wasChanged; /* are the attributes changed? */
1574         int attrs;              /* how many attribute types are in the ads list */
1575         AttributeDescription **ads;
1576 } dninfo;
1577
1578 static int
1579 syncrepl_entry(
1580         syncinfo_t* si,
1581         Operation *op,
1582         Entry* entry,
1583         Modifications** modlist,
1584         int syncstate,
1585         struct berval* syncUUID,
1586         struct sync_cookie* syncCookie_req,
1587         struct berval* syncCSN )
1588 {
1589         Backend *be = op->o_bd;
1590         slap_callback   cb = { NULL, NULL, NULL, NULL };
1591         struct berval   *syncuuid_bv = NULL;
1592         struct berval   syncUUID_strrep = BER_BVNULL;
1593         struct berval   uuid_bv = BER_BVNULL;
1594
1595         SlapReply       rs_search = {REP_RESULT};
1596         SlapReply       rs_delete = {REP_RESULT};
1597         SlapReply       rs_add = {REP_RESULT};
1598         SlapReply       rs_modify = {REP_RESULT};
1599         Filter f = {0};
1600 #ifdef LDAP_COMP_MATCH
1601         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1602 #else
1603         AttributeAssertion ava = { NULL, BER_BVNULL };
1604 #endif
1605         int rc = LDAP_SUCCESS;
1606         int ret = LDAP_SUCCESS;
1607
1608         struct berval pdn = BER_BVNULL;
1609         dninfo dni = {0};
1610         int     retry = 1;
1611
1612         switch( syncstate ) {
1613         case LDAP_SYNC_PRESENT:
1614                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1615                                         "syncrepl_entry",
1616                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1617                 break;
1618         case LDAP_SYNC_ADD:
1619                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1620                                         "syncrepl_entry",
1621                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1622                 break;
1623         case LDAP_SYNC_DELETE:
1624                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1625                                         "syncrepl_entry",
1626                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1627                 break;
1628         case LDAP_SYNC_MODIFY:
1629                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1630                                         "syncrepl_entry",
1631                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1632                 break;
1633         default:
1634                 Debug( LDAP_DEBUG_ANY, "%s: %s\n",
1635                                         "syncrepl_entry",
1636                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1637         }
1638
1639         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1640                 if ( !si->si_refreshPresent ) {
1641                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1642                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1643                                 syncuuid_cmp, avl_dup_error );
1644                 }
1645         }
1646
1647         if ( syncstate == LDAP_SYNC_PRESENT ) {
1648                 return 0;
1649         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1650                 if ( entry == NULL ) {
1651                         return 0;
1652                 }
1653         }
1654
1655         f.f_choice = LDAP_FILTER_EQUALITY;
1656         f.f_ava = &ava;
1657         ava.aa_desc = slap_schema.si_ad_entryUUID;
1658         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1659         ava.aa_value = *syncUUID;
1660         op->ors_filter = &f;
1661
1662         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID->bv_len;
1663         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1664                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1665         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1666         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1667                 syncUUID->bv_val, syncUUID->bv_len );
1668         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1669         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1670
1671         op->o_tag = LDAP_REQ_SEARCH;
1672         op->ors_scope = LDAP_SCOPE_SUBTREE;
1673         op->ors_deref = LDAP_DEREF_NEVER;
1674
1675         /* get the entry for this UUID */
1676         op->o_req_dn = si->si_base;
1677         op->o_req_ndn = si->si_base;
1678
1679         op->o_time = slap_get_time();
1680         op->ors_tlimit = SLAP_NO_LIMIT;
1681         op->ors_slimit = 1;
1682
1683         op->ors_attrs = slap_anlist_all_attributes;
1684         op->ors_attrsonly = 0;
1685
1686         /* set callback function */
1687         op->o_callback = &cb;
1688         cb.sc_response = dn_callback;
1689         cb.sc_private = &dni;
1690         dni.new_entry = entry;
1691
1692         if ( limits_check( op, &rs_search ) == 0 ) {
1693                 rc = be->be_search( op, &rs_search );
1694                 Debug( LDAP_DEBUG_SYNC,
1695                                 "syncrepl_entry: %s (%d)\n", 
1696                                 "be_search", rc, 0 );
1697         }
1698
1699         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1700                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1701         }
1702
1703         cb.sc_response = null_callback;
1704         cb.sc_private = si;
1705
1706         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1707                 Debug( LDAP_DEBUG_SYNC,
1708                                 "syncrepl_entry: %s\n",
1709                                 entry->e_name.bv_val, 0, 0 );
1710         } else {
1711                 Debug( LDAP_DEBUG_SYNC,
1712                                 "syncrepl_entry: %s\n",
1713                                 dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0, 0 );
1714         }
1715
1716         if ( syncstate != LDAP_SYNC_DELETE ) {
1717                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1718
1719                 if ( a == NULL ) {
1720                         /* add if missing */
1721                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1722                                 &syncUUID_strrep, syncUUID );
1723
1724                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1725                         /* replace only if necessary */
1726                         if ( a->a_nvals != a->a_vals ) {
1727                                 ber_memfree( a->a_nvals[0].bv_val );
1728                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1729                         }
1730                         ber_memfree( a->a_vals[0].bv_val );
1731                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1732                 }
1733         }
1734
1735         switch ( syncstate ) {
1736         case LDAP_SYNC_ADD:
1737         case LDAP_SYNC_MODIFY:
1738                 {
1739                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
1740                         if ( a )
1741                                 op->o_csn = a->a_vals[0];
1742                 }
1743 retry_add:;
1744                 if ( BER_BVISNULL( &dni.dn )) {
1745
1746                         op->o_req_dn = entry->e_name;
1747                         op->o_req_ndn = entry->e_nname;
1748                         op->o_tag = LDAP_REQ_ADD;
1749                         op->ora_e = entry;
1750
1751                         rc = be->be_add( op, &rs_add );
1752                         Debug( LDAP_DEBUG_SYNC,
1753                                         "syncrepl_entry: %s (%d)\n", 
1754                                         "be_add", rc, 0 );
1755                         switch ( rs_add.sr_err ) {
1756                         case LDAP_SUCCESS:
1757                                 be_entry_release_w( op, entry );
1758                                 ret = 0;
1759                                 break;
1760
1761                         case LDAP_REFERRAL:
1762                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1763                          * only if the suffix entry is not present */
1764                         case LDAP_NO_SUCH_OBJECT:
1765                                 syncrepl_add_glue( op, entry );
1766                                 ret = 0;
1767                                 break;
1768
1769                         /* if an entry was added via syncrepl_add_glue(),
1770                          * it likely has no entryUUID, so the previous
1771                          * be_search() doesn't find it.  In this case,
1772                          * give syncrepl a chance to modify it. Also
1773                          * allow for entries that were recreated with the
1774                          * same DN but a different entryUUID.
1775                          */
1776                         case LDAP_ALREADY_EXISTS:
1777                                 if ( retry ) {
1778                                         Operation       op2 = *op;
1779                                         SlapReply       rs2 = { 0 };
1780                                         slap_callback   cb2 = { 0 };
1781
1782                                         op2.o_tag = LDAP_REQ_SEARCH;
1783                                         op2.o_req_dn = entry->e_name;
1784                                         op2.o_req_ndn = entry->e_nname;
1785                                         op2.ors_scope = LDAP_SCOPE_BASE;
1786                                         op2.ors_deref = LDAP_DEREF_NEVER;
1787                                         op2.ors_attrs = slap_anlist_all_attributes;
1788                                         op2.ors_attrsonly = 0;
1789                                         op2.ors_limit = NULL;
1790                                         op2.ors_slimit = 1;
1791                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1792
1793                                         f.f_choice = LDAP_FILTER_PRESENT;
1794                                         f.f_desc = slap_schema.si_ad_objectClass;
1795                                         op2.ors_filter = &f;
1796                                         op2.ors_filterstr = generic_filterstr;
1797
1798                                         op2.o_callback = &cb2;
1799                                         cb2.sc_response = dn_callback;
1800                                         cb2.sc_private = &dni;
1801
1802                                         be->be_search( &op2, &rs2 );
1803
1804                                         retry = 0;
1805                                         goto retry_add;
1806                                 }
1807                                 /* FALLTHRU */
1808
1809                         default:
1810                                 Debug( LDAP_DEBUG_ANY,
1811                                         "syncrepl_entry : be_add failed (%d)\n",
1812                                         rs_add.sr_err, 0, 0 );
1813                                 ret = 1;
1814                                 break;
1815                         }
1816                         goto done;
1817                 }
1818                 /* FALLTHRU */
1819                 op->o_req_dn = dni.dn;
1820                 op->o_req_ndn = dni.ndn;
1821                 if ( dni.renamed ) {
1822                         struct berval noldp, newp, nnewp;
1823
1824                         op->o_tag = LDAP_REQ_MODRDN;
1825                         dnRdn( &entry->e_name, &op->orr_newrdn );
1826                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1827
1828                         dnParent( &dni.ndn, &noldp );
1829                         dnParent( &entry->e_nname, &nnewp );
1830                         if ( !dn_match( &noldp, &newp )) {
1831                                 dnParent( &entry->e_name, &newp );
1832                                 op->orr_newSup = &newp;
1833                                 op->orr_nnewSup = &nnewp;
1834                         }
1835                         op->orr_deleteoldrdn = 0;
1836                         rc = be->be_modrdn( op, &rs_modify );
1837                         Debug( LDAP_DEBUG_SYNC,
1838                                         "syncrepl_entry: %s (%d)\n", 
1839                                         "be_modrdn", rc, 0 );
1840                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1841                                 op->o_req_dn = entry->e_name;
1842                                 op->o_req_ndn = entry->e_nname;
1843                         } else {
1844                                 ret = 1;
1845                                 goto done;
1846                         }
1847                 }
1848                 if ( dni.wasChanged ) {
1849                         Modifications *mod, *modhead = NULL;
1850                         Modifications *modtail = NULL;
1851                         int i;
1852
1853                         op->o_tag = LDAP_REQ_MODIFY;
1854
1855                         assert( *modlist != NULL );
1856
1857                         /* Delete all the old attrs */
1858                         for ( i = 0; i < dni.attrs; i++ ) {
1859                                 mod = ch_malloc( sizeof( Modifications ) );
1860                                 mod->sml_op = LDAP_MOD_DELETE;
1861                                 mod->sml_flags = 0;
1862                                 mod->sml_desc = dni.ads[i];
1863                                 mod->sml_type = mod->sml_desc->ad_cname;
1864                                 mod->sml_values = NULL;
1865                                 mod->sml_nvalues = NULL;
1866                                 if ( !modhead ) modhead = mod;
1867                                 if ( modtail ) {
1868                                         modtail->sml_next = mod;
1869                                 }
1870                                 modtail = mod;
1871                         }
1872
1873                         /* Append passed in list to ours */
1874                         if ( modtail ) {
1875                                 modtail->sml_next = *modlist;
1876                                 *modlist = modhead;
1877                         } else {
1878                                 mod = *modlist;
1879                         }
1880
1881                         /* Find end of this list */
1882                         for ( ; mod != NULL; mod = mod->sml_next ) {
1883                                 modtail = mod;
1884                         }
1885
1886                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1887                         mod->sml_op = LDAP_MOD_REPLACE;
1888                         mod->sml_flags = 0;
1889                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1890                         mod->sml_type = mod->sml_desc->ad_cname;
1891                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1892                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1893                         ber_dupbv( &uuid_bv, syncUUID );
1894                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1895                         modtail->sml_next = mod;
1896                                         
1897                         op->o_tag = LDAP_REQ_MODIFY;
1898                         op->orm_modlist = *modlist;
1899
1900                         rc = be->be_modify( op, &rs_modify );
1901                         Debug( LDAP_DEBUG_SYNC,
1902                                         "syncrepl_entry: %s (%d)\n", 
1903                                         "be_modify", rc, 0 );
1904                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1905                                 Debug( LDAP_DEBUG_ANY,
1906                                         "syncrepl_entry : be_modify failed (%d)\n",
1907                                         rs_modify.sr_err, 0, 0 );
1908                         }
1909                 }
1910                 ret = 1;
1911                 goto done;
1912         case LDAP_SYNC_DELETE :
1913                 if ( !BER_BVISNULL( &dni.dn )) {
1914                         op->o_req_dn = dni.dn;
1915                         op->o_req_ndn = dni.ndn;
1916                         op->o_tag = LDAP_REQ_DELETE;
1917                         rc = be->be_delete( op, &rs_delete );
1918                         Debug( LDAP_DEBUG_SYNC,
1919                                         "syncrepl_entry: %s (%d)\n", 
1920                                         "be_delete", rc, 0 );
1921
1922                         while ( rs_delete.sr_err == LDAP_SUCCESS
1923                                 && op->o_delete_glue_parent ) {
1924                                 op->o_delete_glue_parent = 0;
1925                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1926                                         slap_callback cb = { NULL };
1927                                         cb.sc_response = slap_null_cb;
1928                                         dnParent( &op->o_req_ndn, &pdn );
1929                                         op->o_req_dn = pdn;
1930                                         op->o_req_ndn = pdn;
1931                                         op->o_callback = &cb;
1932                                         op->o_bd->be_delete( op, &rs_delete );
1933                                 } else {
1934                                         break;
1935                                 }
1936                         }
1937                 }
1938                 ret = 0;
1939                 goto done;
1940
1941         default :
1942                 Debug( LDAP_DEBUG_ANY,
1943                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1944                 ret = 1;
1945                 goto done;
1946         }
1947
1948 done :
1949         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
1950                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1951                 BER_BVZERO( &syncUUID_strrep );
1952         }
1953         if ( dni.ads ) {
1954                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
1955         }
1956         if ( !BER_BVISNULL( &dni.ndn ) ) {
1957                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
1958         }
1959         if ( !BER_BVISNULL( &dni.dn ) ) {
1960                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
1961         }
1962         BER_BVZERO( &op->o_csn );
1963         return ret;
1964 }
1965
1966 static struct berval gcbva[] = {
1967         BER_BVC("top"),
1968         BER_BVC("glue"),
1969         BER_BVNULL
1970 };
1971
1972 #define NP_DELETE_ONE   2
1973
1974 static void
1975 syncrepl_del_nonpresent(
1976         Operation *op,
1977         syncinfo_t *si,
1978         BerVarray uuids )
1979 {
1980         Backend* be = op->o_bd;
1981         slap_callback   cb = { NULL };
1982         SlapReply       rs_search = {REP_RESULT};
1983         SlapReply       rs_delete = {REP_RESULT};
1984         SlapReply       rs_modify = {REP_RESULT};
1985         struct nonpresent_entry *np_list, *np_prev;
1986         int rc;
1987         AttributeName   an[2];
1988
1989         struct berval pdn = BER_BVNULL;
1990
1991         op->o_req_dn = si->si_base;
1992         op->o_req_ndn = si->si_base;
1993
1994         cb.sc_response = nonpresent_callback;
1995         cb.sc_private = si;
1996
1997         op->o_callback = &cb;
1998         op->o_tag = LDAP_REQ_SEARCH;
1999         op->ors_scope = si->si_scope;
2000         op->ors_deref = LDAP_DEREF_NEVER;
2001         op->o_time = slap_get_time();
2002         op->ors_tlimit = SLAP_NO_LIMIT;
2003
2004
2005         if ( uuids ) {
2006                 Filter uf;
2007 #ifdef LDAP_COMP_MATCH
2008                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2009 #else
2010                 AttributeAssertion eq = { NULL, BER_BVNULL };
2011 #endif
2012                 int i;
2013
2014                 op->ors_attrsonly = 1;
2015                 op->ors_attrs = slap_anlist_no_attrs;
2016                 op->ors_limit = NULL;
2017                 op->ors_filter = &uf;
2018
2019                 uf.f_ava = &eq;
2020                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2021                 uf.f_next = NULL;
2022                 uf.f_choice = LDAP_FILTER_EQUALITY;
2023                 si->si_refreshDelete |= NP_DELETE_ONE;
2024
2025                 for (i=0; uuids[i].bv_val; i++) {
2026                         op->ors_slimit = 1;
2027                         uf.f_av_value = uuids[i];
2028                         rc = be->be_search( op, &rs_search );
2029                 }
2030                 si->si_refreshDelete ^= NP_DELETE_ONE;
2031         } else {
2032                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2033                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2034                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2035                 op->ors_attrs = an;
2036                 op->ors_slimit = SLAP_NO_LIMIT;
2037                 op->ors_attrsonly = 0;
2038                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2039                 op->ors_filterstr = si->si_filterstr;
2040                 op->o_nocaching = 1;
2041
2042                 if ( limits_check( op, &rs_search ) == 0 ) {
2043                         rc = be->be_search( op, &rs_search );
2044                 }
2045                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2046         }
2047
2048         op->o_nocaching = 0;
2049
2050         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2051
2052                 slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
2053
2054                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2055                 while ( np_list != NULL ) {
2056                         LDAP_LIST_REMOVE( np_list, npe_link );
2057                         np_prev = np_list;
2058                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2059                         op->o_tag = LDAP_REQ_DELETE;
2060                         op->o_callback = &cb;
2061                         cb.sc_response = null_callback;
2062                         cb.sc_private = si;
2063                         op->o_req_dn = *np_prev->npe_name;
2064                         op->o_req_ndn = *np_prev->npe_nname;
2065                         rc = op->o_bd->be_delete( op, &rs_delete );
2066
2067                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2068                                 Modifications mod1, mod2;
2069                                 mod1.sml_op = LDAP_MOD_REPLACE;
2070                                 mod1.sml_flags = 0;
2071                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2072                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2073                                 mod1.sml_values = &gcbva[0];
2074                                 mod1.sml_nvalues = NULL;
2075                                 mod1.sml_next = &mod2;
2076
2077                                 mod2.sml_op = LDAP_MOD_REPLACE;
2078                                 mod2.sml_flags = 0;
2079                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2080                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2081                                 mod2.sml_values = &gcbva[1];
2082                                 mod2.sml_nvalues = NULL;
2083                                 mod2.sml_next = NULL;
2084
2085                                 op->o_tag = LDAP_REQ_MODIFY;
2086                                 op->orm_modlist = &mod1;
2087
2088                                 rc = be->be_modify( op, &rs_modify );
2089                         }
2090
2091                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2092                                         op->o_delete_glue_parent ) {
2093                                 op->o_delete_glue_parent = 0;
2094                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
2095                                         slap_callback cb = { NULL };
2096                                         cb.sc_response = slap_null_cb;
2097                                         dnParent( &op->o_req_ndn, &pdn );
2098                                         op->o_req_dn = pdn;
2099                                         op->o_req_ndn = pdn;
2100                                         op->o_callback = &cb;
2101                                         /* give it a root privil ? */
2102                                         op->o_bd->be_delete( op, &rs_delete );
2103                                 } else {
2104                                         break;
2105                             }
2106                         }
2107
2108                         op->o_delete_glue_parent = 0;
2109
2110                         ber_bvfree( np_prev->npe_name );
2111                         ber_bvfree( np_prev->npe_nname );
2112                         ch_free( np_prev );
2113                 }
2114
2115                 slap_graduate_commit_csn( op );
2116         }
2117
2118         return;
2119 }
2120
2121 void
2122 syncrepl_add_glue(
2123         Operation* op,
2124         Entry *e )
2125 {
2126         Backend *be = op->o_bd;
2127         slap_callback cb = { NULL };
2128         Attribute       *a;
2129         int     rc;
2130         int suffrdns;
2131         int i;
2132         struct berval dn = BER_BVNULL;
2133         struct berval ndn = BER_BVNULL;
2134         Entry   *glue;
2135         SlapReply       rs_add = {REP_RESULT};
2136         struct berval   ptr, nptr;
2137         char            *comma;
2138
2139         op->o_tag = LDAP_REQ_ADD;
2140         op->o_callback = &cb;
2141         cb.sc_response = null_callback;
2142         cb.sc_private = NULL;
2143
2144         dn = e->e_name;
2145         ndn = e->e_nname;
2146
2147         /* count RDNs in suffix */
2148         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2149                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2150                         comma++;
2151                         ptr.bv_len -= comma - ptr.bv_val;
2152                         ptr.bv_val = comma;
2153                         i++;
2154                 }
2155                 suffrdns = i;
2156         } else {
2157                 /* suffix is "" */
2158                 suffrdns = 0;
2159         }
2160
2161         /* Start with BE suffix */
2162         ptr = dn;
2163         for ( i = 0; i < suffrdns; i++ ) {
2164                 comma = ber_bvrchr( &ptr, ',' );
2165                 if ( comma != NULL ) {
2166                         ptr.bv_len = comma - ptr.bv_val;
2167                 } else {
2168                         ptr.bv_len = 0;
2169                         break;
2170                 }
2171         }
2172         
2173         if ( !BER_BVISEMPTY( &ptr ) ) {
2174                 dn.bv_len -= ptr.bv_len + 1;
2175                 dn.bv_val += ptr.bv_len + 1;
2176         }
2177
2178         /* the normalizedDNs are always the same length, no counting
2179          * required.
2180          */
2181         nptr = ndn;
2182         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2183                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2184                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2185
2186                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2187
2188         } else {
2189                 nptr.bv_len = 0;
2190         }
2191
2192         while ( ndn.bv_val > e->e_nname.bv_val ) {
2193                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
2194                 ber_dupbv( &glue->e_name, &dn );
2195                 ber_dupbv( &glue->e_nname, &ndn );
2196
2197                 a = ch_calloc( 1, sizeof( Attribute ));
2198                 a->a_desc = slap_schema.si_ad_objectClass;
2199
2200                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
2201                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2202                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2203                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2204
2205                 a->a_nvals = a->a_vals;
2206
2207                 a->a_next = glue->e_attrs;
2208                 glue->e_attrs = a;
2209
2210                 a = ch_calloc( 1, sizeof( Attribute ));
2211                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
2212
2213                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
2214                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2215                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2216
2217                 a->a_nvals = a->a_vals;
2218
2219                 a->a_next = glue->e_attrs;
2220                 glue->e_attrs = a;
2221
2222                 op->o_req_dn = glue->e_name;
2223                 op->o_req_ndn = glue->e_nname;
2224                 op->ora_e = glue;
2225                 rc = be->be_add ( op, &rs_add );
2226                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2227                         be_entry_release_w( op, glue );
2228                 } else {
2229                 /* incl. ALREADY EXIST */
2230                         entry_free( glue );
2231                 }
2232
2233                 /* Move to next child */
2234                 comma = ber_bvrchr( &ptr, ',' );
2235                 if ( comma == NULL ) {
2236                         break;
2237                 }
2238                 ptr.bv_len = comma - ptr.bv_val;
2239                 
2240                 dn.bv_val = ++comma;
2241                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2242
2243                 comma = ber_bvrchr( &nptr, ',' );
2244                 assert( comma != NULL );
2245                 nptr.bv_len = comma - nptr.bv_val;
2246
2247                 ndn.bv_val = ++comma;
2248                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2249         }
2250
2251         op->o_req_dn = e->e_name;
2252         op->o_req_ndn = e->e_nname;
2253         op->ora_e = e;
2254         rc = be->be_add ( op, &rs_add );
2255         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2256                 be_entry_release_w( op, e );
2257         } else {
2258                 entry_free( e );
2259         }
2260
2261         return;
2262 }
2263
2264 static void
2265 syncrepl_updateCookie(
2266         syncinfo_t *si,
2267         Operation *op,
2268         struct berval *pdn,
2269         struct sync_cookie *syncCookie )
2270 {
2271         Backend *be = op->o_bd;
2272         Modifications mod = { { 0 } };
2273         struct berval vals[ 2 ];
2274
2275         int rc;
2276
2277         slap_callback cb = { NULL };
2278         SlapReply       rs_modify = {REP_RESULT};
2279
2280         slap_sync_cookie_free( &si->si_syncCookie, 0 );
2281         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2282
2283         mod.sml_op = LDAP_MOD_REPLACE;
2284         mod.sml_desc = slap_schema.si_ad_contextCSN;
2285         mod.sml_type = mod.sml_desc->ad_cname;
2286         mod.sml_values = vals;
2287         vals[0] = si->si_syncCookie.ctxcsn;
2288         vals[1].bv_val = NULL;
2289         vals[1].bv_len = 0;
2290
2291         slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
2292
2293         op->o_tag = LDAP_REQ_MODIFY;
2294
2295         assert( si->si_rid < 1000 );
2296
2297         cb.sc_response = null_callback;
2298         cb.sc_private = si;
2299
2300         op->o_callback = &cb;
2301         op->o_req_dn = op->o_bd->be_suffix[0];
2302         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2303
2304         /* update contextCSN */
2305         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2306         op->orm_modlist = &mod;
2307         rc = be->be_modify( op, &rs_modify );
2308         op->o_msgid = 0;
2309
2310         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2311                 Debug( LDAP_DEBUG_ANY,
2312                         "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
2313         }
2314
2315         slap_graduate_commit_csn( op );
2316
2317         return;
2318 }
2319
2320 static int
2321 dn_callback(
2322         Operation*      op,
2323         SlapReply*      rs )
2324 {
2325         dninfo *dni = op->o_callback->sc_private;
2326
2327         if ( rs->sr_type == REP_SEARCH ) {
2328                 if ( !BER_BVISNULL( &dni->dn ) ) {
2329                         Debug( LDAP_DEBUG_ANY,
2330                                 "dn_callback : consistency error - "
2331                                 "entryUUID is not unique\n", 0, 0, 0 );
2332                 } else {
2333                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2334                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2335                         /* If there is a new entry, see if it differs from the old.
2336                          * We compare the non-normalized values so that cosmetic changes
2337                          * in the provider are always propagated.
2338                          */
2339                         if ( dni->new_entry ) {
2340                                 Attribute *old, *new;
2341                                 int i;
2342
2343                                 /* Did the DN change? Note that we don't explicitly try to
2344                                  * discover if the deleteOldRdn argument applies here. It
2345                                  * would save an unnecessary Modify if we detected it, but
2346                                  * that's a fair amount of trouble to compare the two attr
2347                                  * lists in detail. (Just test normalized DN; we ignore
2348                                  * insignificant changes here.)
2349                                  */
2350                                 if ( !dn_match( &rs->sr_entry->e_nname,
2351                                                 &dni->new_entry->e_nname ) )
2352                                 {
2353                                         dni->renamed = 1;
2354                                 }
2355
2356                                 for ( i = 0, old = rs->sr_entry->e_attrs;
2357                                                 old;
2358                                                 i++, old = old->a_next )
2359                                         ;
2360
2361                                 dni->attrs = i;
2362
2363                                 /* We assume that attributes are saved in the same order
2364                                  * in the remote and local databases. So if we walk through
2365                                  * the attributeDescriptions one by one they should match in
2366                                  * lock step. If not, we signal a change. Otherwise we test
2367                                  * all the values...
2368                                  */
2369                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2370                                                 old && new;
2371                                                 old = old->a_next, new = new->a_next )
2372                                 {
2373                                         if ( old->a_desc != new->a_desc ) {
2374                                                 dni->wasChanged = 1;
2375                                                 break;
2376                                         }
2377                                         for ( i = 0; ; i++ ) {
2378                                                 int nold, nnew;
2379                                                 nold = BER_BVISNULL( &old->a_vals[i] );
2380                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
2381                                                 /* If both are empty, stop looking */
2382                                                 if ( nold && nnew ) {
2383                                                         break;
2384                                                 }
2385                                                 /* If they are different, stop looking */
2386                                                 if ( nold != nnew ) {
2387                                                         dni->wasChanged = 1;
2388                                                         break;
2389                                                 }
2390                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
2391                                                         dni->wasChanged = 1;
2392                                                         break;
2393                                                 }
2394                                         }
2395                                         if ( dni->wasChanged ) break;
2396                                 }
2397                                 if ( dni->wasChanged ) {
2398                                         dni->ads = op->o_tmpalloc( dni->attrs *
2399                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2400                                         i = 0;
2401                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2402                                                 dni->ads[i] = old->a_desc;
2403                                                 i++;
2404                                         }
2405                                 }
2406                         }
2407                 }
2408         } else if ( rs->sr_type == REP_RESULT ) {
2409                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2410                         Debug( LDAP_DEBUG_ANY,
2411                                 "dn_callback : consistency error - "
2412                                 "entryUUID is not unique\n", 0, 0, 0 );
2413                 }
2414         }
2415
2416         return LDAP_SUCCESS;
2417 }
2418
2419 static int
2420 nonpresent_callback(
2421         Operation*      op,
2422         SlapReply*      rs )
2423 {
2424         syncinfo_t *si = op->o_callback->sc_private;
2425         Attribute *a;
2426         int count = 0;
2427         struct berval* present_uuid = NULL;
2428         struct nonpresent_entry *np_entry;
2429
2430         if ( rs->sr_type == REP_RESULT ) {
2431                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2432                 si->si_presentlist = NULL;
2433
2434         } else if ( rs->sr_type == REP_SEARCH ) {
2435                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2436                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2437
2438                         if ( a == NULL ) return 0;
2439
2440                         present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2441                                 syncuuid_cmp );
2442                 }
2443
2444                 if ( present_uuid == NULL ) {
2445                         np_entry = (struct nonpresent_entry *)
2446                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2447                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2448                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2449                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2450
2451                 } else {
2452                         avl_delete( &si->si_presentlist,
2453                                         &a->a_nvals[0], syncuuid_cmp );
2454                         ch_free( present_uuid->bv_val );
2455                         ch_free( present_uuid );
2456                 }
2457         }
2458         return LDAP_SUCCESS;
2459 }
2460
2461 static int
2462 null_callback(
2463         Operation*      op,
2464         SlapReply*      rs )
2465 {
2466         if ( rs->sr_err != LDAP_SUCCESS &&
2467                 rs->sr_err != LDAP_REFERRAL &&
2468                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2469                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2470                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2471         {
2472                 Debug( LDAP_DEBUG_ANY,
2473                         "null_callback : error code 0x%x\n",
2474                         rs->sr_err, 0, 0 );
2475         }
2476         return LDAP_SUCCESS;
2477 }
2478
2479 static struct berval *
2480 slap_uuidstr_from_normalized(
2481         struct berval* uuidstr,
2482         struct berval* normalized,
2483         void *ctx )
2484 {
2485         struct berval *new;
2486         unsigned char nibble;
2487         int i, d = 0;
2488
2489         if ( normalized == NULL ) return NULL;
2490         if ( normalized->bv_len != 16 ) return NULL;
2491
2492         if ( uuidstr ) {
2493                 new = uuidstr;
2494         } else {
2495                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2496                 if ( new == NULL ) {
2497                         return NULL;
2498                 }
2499         }
2500
2501         new->bv_len = 36;
2502
2503         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2504                 if ( new != uuidstr ) {
2505                         slap_sl_free( new, ctx );
2506                 }
2507                 return NULL;
2508         }
2509
2510         for ( i = 0; i < 16; i++ ) {
2511                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2512                         new->bv_val[(i<<1)+d] = '-';
2513                         d += 1;
2514                 }
2515
2516                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2517                 if ( nibble < 10 ) {
2518                         new->bv_val[(i<<1)+d] = nibble + '0';
2519                 } else {
2520                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2521                 }
2522
2523                 nibble = (normalized->bv_val[i]) & 0xF;
2524                 if ( nibble < 10 ) {
2525                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2526                 } else {
2527                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2528                 }
2529         }
2530
2531         new->bv_val[new->bv_len] = '\0';
2532         return new;
2533 }
2534
2535 static int
2536 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2537 {
2538         const struct berval *uuid1 = v_uuid1;
2539         const struct berval *uuid2 = v_uuid2;
2540         int rc = uuid1->bv_len - uuid2->bv_len;
2541         if ( rc ) return rc;
2542         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2543 }
2544
2545 static void
2546 avl_ber_bvfree( void *v_bv )
2547 {
2548         struct berval   *bv = (struct berval *)v_bv;
2549         
2550         if( v_bv == NULL ) return;
2551         if ( !BER_BVISNULL( bv ) ) {
2552                 ch_free( bv->bv_val );
2553         }
2554         ch_free( (char *) bv );
2555 }
2556
2557 void
2558 syncinfo_free( syncinfo_t *sie )
2559 {
2560         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
2561
2562         bindconf_free( &sie->si_bindconf );
2563
2564         if ( sie->si_filterstr.bv_val ) {
2565                 ch_free( sie->si_filterstr.bv_val );
2566         }
2567         if ( sie->si_base.bv_val ) {
2568                 ch_free( sie->si_base.bv_val );
2569         }
2570         if ( sie->si_attrs ) {
2571                 int i = 0;
2572                 while ( sie->si_attrs[i] != NULL ) {
2573                         ch_free( sie->si_attrs[i] );
2574                         i++;
2575                 }
2576                 ch_free( sie->si_attrs );
2577         }
2578         if ( sie->si_exattrs ) {
2579                 int i = 0;
2580                 while ( sie->si_exattrs[i] != NULL ) {
2581                         ch_free( sie->si_exattrs[i] );
2582                         i++;
2583                 }
2584                 ch_free( sie->si_exattrs );
2585         }
2586         if ( sie->si_anlist ) {
2587                 int i = 0;
2588                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2589                         ch_free( sie->si_anlist[i].an_name.bv_val );
2590                         i++;
2591                 }
2592                 ch_free( sie->si_anlist );
2593         }
2594         if ( sie->si_exanlist ) {
2595                 int i = 0;
2596                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2597                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2598                         i++;
2599                 }
2600                 ch_free( sie->si_exanlist );
2601         }
2602         if ( sie->si_retryinterval ) {
2603                 ch_free( sie->si_retryinterval );
2604         }
2605         if ( sie->si_retrynum ) {
2606                 ch_free( sie->si_retrynum );
2607         }
2608         if ( sie->si_retrynum_init ) {
2609                 ch_free( sie->si_retrynum_init );
2610         }
2611         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2612         if ( sie->si_presentlist ) {
2613             avl_free( sie->si_presentlist, avl_ber_bvfree );
2614         }
2615         if ( sie->si_ld ) {
2616                 ldap_unbind_ext( sie->si_ld, NULL, NULL );
2617         }
2618         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2619                 struct nonpresent_entry* npe;
2620                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2621                 LDAP_LIST_REMOVE( npe, npe_link );
2622                 if ( npe->npe_name ) {
2623                         if ( npe->npe_name->bv_val ) {
2624                                 ch_free( npe->npe_name->bv_val );
2625                         }
2626                         ch_free( npe->npe_name );
2627                 }
2628                 if ( npe->npe_nname ) {
2629                         if ( npe->npe_nname->bv_val ) {
2630                                 ch_free( npe->npe_nname->bv_val );
2631                         }
2632                         ch_free( npe->npe_nname );
2633                 }
2634                 ch_free( npe );
2635         }
2636         ch_free( sie );
2637 }
2638
2639
2640
2641 /* NOTE: used & documented in slapd.conf(5) */
2642 #define IDSTR                   "rid"
2643 #define PROVIDERSTR             "provider"
2644 #define SCHEMASTR               "schemachecking"
2645 #define FILTERSTR               "filter"
2646 #define SEARCHBASESTR           "searchbase"
2647 #define SCOPESTR                "scope"
2648 #define ATTRSONLYSTR            "attrsonly"
2649 #define ATTRSSTR                "attrs"
2650 #define TYPESTR                 "type"
2651 #define INTERVALSTR             "interval"
2652 #define RETRYSTR                "retry"
2653 #define SLIMITSTR               "sizelimit"
2654 #define TLIMITSTR               "timelimit"
2655 #define SYNCDATASTR             "syncdata"
2656
2657 /* FIXME: undocumented */
2658 #define LOGBASESTR      "logbase"
2659 #define LOGFILTERSTR    "logfilter"
2660 #define OLDAUTHCSTR             "bindprincipal"
2661 #define EXATTRSSTR              "exattrs"
2662 #define MANAGEDSAITSTR          "manageDSAit"
2663
2664 /* FIXME: unused */
2665 #define LASTMODSTR              "lastmod"
2666 #define LMGENSTR                "gen"
2667 #define LMNOSTR                 "no"
2668 #define LMREQSTR                "req"
2669 #define SRVTABSTR               "srvtab"
2670 #define SUFFIXSTR               "suffix"
2671
2672 /* mandatory */
2673 #define GOT_ID                  0x0001
2674 #define GOT_PROVIDER            0x0002
2675
2676 /* check */
2677 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER)
2678
2679 static struct {
2680         struct berval key;
2681         int val;
2682 } scopes[] = {
2683         { BER_BVC("base"), LDAP_SCOPE_BASE },
2684         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
2685         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
2686         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
2687         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
2688         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
2689         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
2690         { BER_BVNULL, 0 }
2691 };
2692
2693 static slap_verbmasks datamodes[] = {
2694         { BER_BVC("default"), SYNCDATA_DEFAULT },
2695         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
2696         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
2697         { BER_BVNULL, 0 }
2698 };
2699
2700 static int
2701 parse_syncrepl_line(
2702         ConfigArgs      *c,
2703         syncinfo_t      *si )
2704 {
2705         int     gots = 0;
2706         int     i;
2707         char    *val;
2708
2709         for ( i = 1; i < c->argc; i++ ) {
2710                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
2711                                         STRLENOF( IDSTR "=" ) ) )
2712                 {
2713                         int tmp;
2714                         /* '\0' string terminator accounts for '=' */
2715                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
2716                         if ( lutil_atoi( &tmp, val ) != 0 ) {
2717                                 snprintf( c->msg, sizeof( c->msg ),
2718                                         "Error: parse_syncrepl_line: "
2719                                         "unable to parse syncrepl id \"%s\"", val );
2720                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2721                                 return -1;
2722                         }
2723                         if ( tmp >= 1000 || tmp < 0 ) {
2724                                 snprintf( c->msg, sizeof( c->msg ),
2725                                         "Error: parse_syncrepl_line: "
2726                                         "syncrepl id %d is out of range [0..999]", tmp );
2727                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2728                                 return -1;
2729                         }
2730                         si->si_rid = tmp;
2731                         gots |= GOT_ID;
2732                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
2733                                         STRLENOF( PROVIDERSTR "=" ) ) )
2734                 {
2735                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
2736                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
2737                         gots |= GOT_PROVIDER;
2738                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
2739                                         STRLENOF( SCHEMASTR "=" ) ) )
2740                 {
2741                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
2742                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) )) {
2743                                 si->si_schemachecking = 1;
2744                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
2745                                 si->si_schemachecking = 0;
2746                         } else {
2747                                 si->si_schemachecking = 1;
2748                         }
2749                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
2750                                         STRLENOF( FILTERSTR "=" ) ) )
2751                 {
2752                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
2753                         if ( si->si_filterstr.bv_val )
2754                                 ch_free( si->si_filterstr.bv_val );
2755                         ber_str2bv( val, 0, 1, &si->si_filterstr );
2756                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
2757                                         STRLENOF( LOGFILTERSTR "=" ) ) )
2758                 {
2759                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
2760                         if ( si->si_logfilterstr.bv_val )
2761                                 ch_free( si->si_logfilterstr.bv_val );
2762                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
2763                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
2764                                         STRLENOF( SEARCHBASESTR "=" ) ) )
2765                 {
2766                         struct berval   bv;
2767                         int             rc;
2768
2769                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
2770                         if ( si->si_base.bv_val ) {
2771                                 ch_free( si->si_base.bv_val );
2772                         }
2773                         ber_str2bv( val, 0, 0, &bv );
2774                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
2775                         if ( rc != LDAP_SUCCESS ) {
2776                                 snprintf( c->msg, sizeof( c->msg ),
2777                                         "Invalid base DN \"%s\": %d (%s)",
2778                                         val, rc, ldap_err2string( rc ) );
2779                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2780                                 return -1;
2781                         }
2782                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
2783                                         STRLENOF( LOGBASESTR "=" ) ) )
2784                 {
2785                         struct berval   bv;
2786                         int             rc;
2787
2788                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
2789                         if ( si->si_logbase.bv_val ) {
2790                                 ch_free( si->si_logbase.bv_val );
2791                         }
2792                         ber_str2bv( val, 0, 0, &bv );
2793                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
2794                         if ( rc != LDAP_SUCCESS ) {
2795                                 snprintf( c->msg, sizeof( c->msg ),
2796                                         "Invalid logbase DN \"%s\": %d (%s)",
2797                                         val, rc, ldap_err2string( rc ) );
2798                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2799                                 return -1;
2800                         }
2801                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
2802                                         STRLENOF( SCOPESTR "=" ) ) )
2803                 {
2804                         int j;
2805                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
2806                         for ( j=0; !BER_BVISNULL(&scopes[j].key); j++ ) {
2807                                 if (!strcasecmp( val, scopes[j].key.bv_val )) {
2808                                         si->si_scope = scopes[j].val;
2809                                         break;
2810                                 }
2811                         }
2812                         if ( BER_BVISNULL(&scopes[j].key) ) {
2813                                 snprintf( c->msg, sizeof( c->msg ),
2814                                         "Error: parse_syncrepl_line: "
2815                                         "unknown scope \"%s\"", val);
2816                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2817                                 return -1;
2818                         }
2819                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR "=",
2820                                         STRLENOF( ATTRSONLYSTR "=" ) ) )
2821                 {
2822                         si->si_attrsonly = 1;
2823                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
2824                                         STRLENOF( ATTRSSTR "=" ) ) )
2825                 {
2826                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
2827                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
2828                                 char *attr_fname;
2829                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2830                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
2831                                 if ( si->si_anlist == NULL ) {
2832                                         ch_free( attr_fname );
2833                                         return -1;
2834                                 }
2835                                 si->si_anfile = attr_fname;
2836                         } else {
2837                                 char *str, *s, *next;
2838                                 char delimstr[] = " ,\t";
2839                                 str = ch_strdup( val );
2840                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
2841                                                 s != NULL;
2842                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
2843                                 {
2844                                         if ( strlen(s) == 1 && *s == '*' ) {
2845                                                 si->si_allattrs = 1;
2846                                                 *(val + ( s - str )) = delimstr[0];
2847                                         }
2848                                         if ( strlen(s) == 1 && *s == '+' ) {
2849                                                 si->si_allopattrs = 1;
2850                                                 *(val + ( s - str )) = delimstr[0];
2851                                         }
2852                                 }
2853                                 ch_free( str );
2854                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
2855                                 if ( si->si_anlist == NULL ) {
2856                                         return -1;
2857                                 }
2858                         }
2859                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
2860                                         STRLENOF( EXATTRSSTR "=" ) ) )
2861                 {
2862                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
2863                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") )) {
2864                                 char *attr_fname;
2865                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2866                                 si->si_exanlist = file2anlist(
2867                                         si->si_exanlist, attr_fname, " ,\t" );
2868                                 if ( si->si_exanlist == NULL ) {
2869                                         ch_free( attr_fname );
2870                                         return -1;
2871                                 }
2872                                 ch_free( attr_fname );
2873                         } else {
2874                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
2875                                 if ( si->si_exanlist == NULL ) {
2876                                         return -1;
2877                                 }
2878                         }
2879                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
2880                                         STRLENOF( TYPESTR "=" ) ) )
2881                 {
2882                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
2883                         if ( !strncasecmp( val, "refreshOnly",
2884                                                 STRLENOF("refreshOnly") ) )
2885                         {
2886                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
2887                         } else if ( !strncasecmp( val, "refreshAndPersist",
2888                                                 STRLENOF("refreshAndPersist") ) )
2889                         {
2890                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
2891                                 si->si_interval = 60;
2892                         } else {
2893                                 snprintf( c->msg, sizeof( c->msg ),
2894                                         "Error: parse_syncrepl_line: "
2895                                         "unknown sync type \"%s\"", val);
2896                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2897                                 return -1;
2898                         }
2899                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
2900                                         STRLENOF( INTERVALSTR "=" ) ) )
2901                 {
2902                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
2903                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
2904                                 si->si_interval = 0;
2905                         } else if ( strchr( val, ':' ) != NULL ) {
2906                                 char *next, *ptr = val;
2907                                 unsigned dd, hh, mm, ss;
2908                                 dd = strtoul( ptr, &next, 10 );
2909                                 if ( next == ptr || next[0] != ':' ) {
2910                                         snprintf( c->msg, sizeof( c->msg ),
2911                                                 "Error: parse_syncrepl_line: "
2912                                                 "invalid interval \"%s\", unable to parse days", val );
2913                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2914                                         return -1;
2915                                 }
2916                                 ptr = next + 1;
2917                                 hh = strtoul( ptr, &next, 10 );
2918                                 if ( next == ptr || next[0] != ':' || hh > 24 ) {
2919                                         snprintf( c->msg, sizeof( c->msg ),
2920                                                 "Error: parse_syncrepl_line: "
2921                                                 "invalid interval \"%s\", unable to parse hours", val );
2922                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2923                                         return -1;
2924                                 }
2925                                 ptr = next + 1;
2926                                 mm = strtoul( ptr, &next, 10 );
2927                                 if ( next == ptr || next[0] != ':' || mm > 60 ) {
2928                                         snprintf( c->msg, sizeof( c->msg ),
2929                                                 "Error: parse_syncrepl_line: "
2930                                                 "invalid interval \"%s\", unable to parse minutes", val );
2931                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2932                                         return -1;
2933                                 }
2934                                 ptr = next + 1;
2935                                 ss = strtoul( ptr, &next, 10 );
2936                                 if ( next == ptr || next[0] != '\0' || ss > 60 ) {
2937                                         snprintf( c->msg, sizeof( c->msg ),
2938                                                 "Error: parse_syncrepl_line: "
2939                                                 "invalid interval \"%s\", unable to parse seconds", val );
2940                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2941                                         return -1;
2942                                 }
2943                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
2944                         } else {
2945                                 unsigned long   t;
2946
2947                                 if ( lutil_parse_time( val, &t ) != 0 ) {
2948                                         snprintf( c->msg, sizeof( c->msg ),
2949                                                 "Error: parse_syncrepl_line: "
2950                                                 "invalid interval \"%s\"", val );
2951                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2952                                         return -1;
2953                                 }
2954                                 si->si_interval = (time_t)t;
2955                         }
2956                         if ( si->si_interval < 0 ) {
2957                                 snprintf( c->msg, sizeof( c->msg ),
2958                                         "Error: parse_syncrepl_line: "
2959                                         "invalid interval \"%ld\"",
2960                                         (long) si->si_interval);
2961                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2962                                 return -1;
2963                         }
2964                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
2965                                         STRLENOF( RETRYSTR "=" ) ) )
2966                 {
2967                         char **retry_list;
2968                         int j, k, n;
2969
2970                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
2971                         retry_list = (char **) ch_calloc( 1, sizeof( char * ));
2972                         retry_list[0] = NULL;
2973
2974                         slap_str2clist( &retry_list, val, " ,\t" );
2975
2976                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
2977                         n = k / 2;
2978                         if ( k % 2 ) {
2979                                 snprintf( c->msg, sizeof( c->msg ),
2980                                         "Error: incomplete syncrepl retry list" );
2981                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2982                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
2983                                         ch_free( retry_list[k] );
2984                                 }
2985                                 ch_free( retry_list );
2986                                 return 1;
2987                         }
2988                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ));
2989                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ));
2990                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ));
2991                         for ( j = 0; j < n; j++ ) {
2992                                 unsigned long   t;
2993                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
2994                                         snprintf( c->msg, sizeof( c->msg ),
2995                                                 "Error: invalid retry interval \"%s\" (#%d)",
2996                                                 retry_list[j*2], j );
2997                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2998                                         /* do some cleanup */
2999                                         return 1;
3000                                 }
3001                                 si->si_retryinterval[j] = (time_t)t;
3002                                 if ( *retry_list[j*2+1] == '+' ) {
3003                                         si->si_retrynum_init[j] = -1;
3004                                         si->si_retrynum[j] = -1;
3005                                         j++;
3006                                         break;
3007                                 } else {
3008                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0 ) {
3009                                                 snprintf( c->msg, sizeof( c->msg ),
3010                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3011                                                         retry_list[j*2+1], j );
3012                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3013                                                 /* do some cleanup */
3014                                                 return 1;
3015                                         }
3016                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0 ) {
3017                                                 snprintf( c->msg, sizeof( c->msg ),
3018                                                         "Error: invalid retry number \"%s\" (#%d)",
3019                                                         retry_list[j*2+1], j );
3020                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3021                                                 /* do some cleanup */
3022                                                 return 1;
3023                                         }
3024                                 }
3025                         }
3026                         si->si_retrynum_init[j] = -2;
3027                         si->si_retrynum[j] = -2;
3028                         si->si_retryinterval[j] = 0;
3029                         
3030                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3031                                 ch_free( retry_list[k] );
3032                         }
3033                         ch_free( retry_list );
3034                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3035                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3036                 {
3037                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3038                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3039                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3040                         {
3041                                 snprintf( c->msg, sizeof( c->msg ),
3042                                         "invalid manageDSAit value \"%s\".\n",
3043                                         val );
3044                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3045                                 return 1;
3046                         }
3047                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3048                                         STRLENOF( SLIMITSTR "=") ) )
3049                 {
3050                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3051                         if ( lutil_atoi( &si->si_slimit, val ) != 0 ) {
3052                                 snprintf( c->msg, sizeof( c->msg ),
3053                                         "invalid size limit value \"%s\".\n",
3054                                         val );
3055                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3056                                 return 1;
3057                         }
3058                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3059                                         STRLENOF( TLIMITSTR "=" ) ) )
3060                 {
3061                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3062                         if ( lutil_atoi( &si->si_tlimit, val ) != 0 ) {
3063                                 snprintf( c->msg, sizeof( c->msg ),
3064                                         "invalid time limit value \"%s\".\n",
3065                                         val );
3066                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3067                                 return 1;
3068                         }
3069                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3070                                         STRLENOF( SYNCDATASTR "=" ) ) )
3071                 {
3072                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3073                         si->si_syncdata = verb_to_mask( val, datamodes );
3074                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3075                         snprintf( c->msg, sizeof( c->msg ),
3076                                 "Error: parse_syncrepl_line: "
3077                                 "unknown keyword \"%s\"\n", c->argv[ i ] );
3078                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3079                         return -1;
3080                 }
3081         }
3082
3083         if ( gots != GOT_ALL ) {
3084                 snprintf( c->msg, sizeof( c->msg ),
3085                         "Error: Malformed \"syncrepl\" line in slapd config file" );
3086                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3087                 return -1;
3088         }
3089
3090         return 0;
3091 }
3092
3093 static int
3094 add_syncrepl(
3095         ConfigArgs *c )
3096 {
3097         syncinfo_t *si;
3098         int     rc = 0;
3099
3100         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3101                 Debug( LDAP_DEBUG_ANY, "%s: database %s does not support operations "
3102                         "required for syncrepl\n", c->log, c->be->be_type, 0 );
3103                 return 1;
3104         }
3105         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3106
3107         if ( si == NULL ) {
3108                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3109                 return 1;
3110         }
3111
3112         si->si_bindconf.sb_tls = SB_TLS_OFF;
3113         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3114         si->si_schemachecking = 0;
3115         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3116                 &si->si_filterstr );
3117         si->si_base.bv_val = NULL;
3118         si->si_scope = LDAP_SCOPE_SUBTREE;
3119         si->si_attrsonly = 0;
3120         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3121         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3122         si->si_attrs = NULL;
3123         si->si_allattrs = 0;
3124         si->si_allopattrs = 0;
3125         si->si_exattrs = NULL;
3126         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3127         si->si_interval = 86400;
3128         si->si_retryinterval = NULL;
3129         si->si_retrynum_init = NULL;
3130         si->si_retrynum = NULL;
3131         si->si_manageDSAit = 0;
3132         si->si_tlimit = 0;
3133         si->si_slimit = 0;
3134         si->si_conn_setup = 0;
3135
3136         si->si_presentlist = NULL;
3137         LDAP_LIST_INIT( &si->si_nonpresentlist );
3138         ldap_pvt_thread_mutex_init( &si->si_mutex );
3139
3140         rc = parse_syncrepl_line( c, si );
3141
3142         if ( rc == 0 ) {
3143                 si->si_be = c->be;
3144                 init_syncrepl( si );
3145                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq, si->si_interval,
3146                         do_syncrepl, si, "do_syncrepl", c->be->be_suffix[0].bv_val );
3147                 if ( !si->si_re )
3148                         rc = -1;
3149         }
3150         if ( rc < 0 ) {
3151                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3152                 syncinfo_free( si );    
3153                 return 1;
3154         } else {
3155                 Debug( LDAP_DEBUG_CONFIG,
3156                         "Config: ** successfully added syncrepl \"%s\"\n",
3157                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3158                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3159                 if ( !si->si_schemachecking ) {
3160                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3161                 }
3162                 c->be->be_syncinfo = si;
3163                 return 0;
3164         }
3165 }
3166
3167 static void
3168 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3169 {
3170         struct berval bc, uri;
3171         char buf[BUFSIZ*2], *ptr;
3172         int i;
3173
3174         /* temporarily inhibit bindconf from printing URI */
3175         uri = si->si_bindconf.sb_uri;
3176         BER_BVZERO( &si->si_bindconf.sb_uri );
3177         bindconf_unparse( &si->si_bindconf, &bc );
3178         si->si_bindconf.sb_uri = uri;
3179
3180         ptr = buf;
3181         ptr += snprintf( ptr, sizeof( buf ), IDSTR "=%03ld " PROVIDERSTR "=%s",
3182                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3183         if ( !BER_BVISNULL( &bc )) {
3184                 ptr = lutil_strcopy( ptr, bc.bv_val );
3185                 free( bc.bv_val );
3186         }
3187         if ( !BER_BVISEMPTY( &si->si_filterstr )) {
3188                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3189                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3190                 *ptr++ = '"';
3191         }
3192         if ( !BER_BVISNULL( &si->si_base )) {
3193                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3194                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3195                 *ptr++ = '"';
3196         }
3197         if ( !BER_BVISEMPTY( &si->si_logfilterstr )) {
3198                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3199                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3200                 *ptr++ = '"';
3201         }
3202         if ( !BER_BVISNULL( &si->si_logbase )) {
3203                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3204                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3205                 *ptr++ = '"';
3206         }
3207         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3208                 if ( si->si_scope == scopes[i].val ) {
3209                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3210                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3211                         break;
3212                 }
3213         }
3214         if ( si->si_attrsonly ) {
3215                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR "=yes" );
3216         }
3217         if ( si->si_anfile ) {
3218                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:" );
3219                 ptr = lutil_strcopy( ptr, si->si_anfile );
3220         } else if ( si->si_allattrs || si->si_allopattrs ||
3221                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) )) {
3222                 char *old;
3223                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3224                 old = ptr;
3225                 ptr = anlist_unparse( si->si_anlist, ptr );
3226                 if ( si->si_allattrs ) {
3227                         if ( old != ptr ) *ptr++ = ',';
3228                         *ptr++ = '*';
3229                 }
3230                 if ( si->si_allopattrs ) {
3231                         if ( old != ptr ) *ptr++ = ',';
3232                         *ptr++ = '+';
3233                 }
3234                 *ptr++ = '"';
3235         }
3236         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3237                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3238                 ptr = anlist_unparse( si->si_exanlist, ptr );
3239         }
3240         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3241         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3242         
3243         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3244         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3245                 "refreshAndPersist" : "refreshOnly" );
3246
3247         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3248                 int dd, hh, mm, ss;
3249
3250                 dd = si->si_interval;
3251                 ss = dd % 60;
3252                 dd /= 60;
3253                 mm = dd % 60;
3254                 dd /= 60;
3255                 hh = dd % 24;
3256                 dd /= 24;
3257                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3258                 ptr += sprintf( ptr, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3259         } else if ( si->si_retryinterval ) {
3260                 int space=0;
3261                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3262                 for (i=0; si->si_retryinterval[i]; i++) {
3263                         if ( space ) *ptr++ = ' ';
3264                         space = 1;
3265                         ptr += sprintf( ptr, "%ld ", (long) si->si_retryinterval[i] );
3266                         if ( si->si_retrynum_init[i] == -1 )
3267                                 *ptr++ = '+';
3268                         else
3269                                 ptr += sprintf( ptr, "%d", si->si_retrynum_init[i] );
3270                 }
3271                 *ptr++ = '"';
3272         }
3273
3274         if ( si->si_slimit ) {
3275                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3276                 ptr += sprintf( ptr, "%d", si->si_slimit );
3277         }
3278
3279         if ( si->si_tlimit ) {
3280                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3281                 ptr += sprintf( ptr, "%d", si->si_tlimit );
3282         }
3283
3284         if ( si->si_syncdata ) {
3285                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3286                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3287                         ptr = lutil_strcopy( ptr, bc.bv_val );
3288                 }
3289         }
3290         bc.bv_len = ptr - buf;
3291         bc.bv_val = buf;
3292         ber_dupbv( bv, &bc );
3293 }
3294
3295 int
3296 syncrepl_config( ConfigArgs *c )
3297 {
3298         if (c->op == SLAP_CONFIG_EMIT) {
3299                 if ( c->be->be_syncinfo ) {
3300                         struct berval bv;
3301                         syncrepl_unparse( c->be->be_syncinfo, &bv ); 
3302                         ber_bvarray_add( &c->rvalue_vals, &bv );
3303                         return 0;
3304                 }
3305                 return 1;
3306         } else if ( c->op == LDAP_MOD_DELETE ) {
3307                 struct re_s *re;
3308
3309                 if ( c->be->be_syncinfo ) {
3310                         re = c->be->be_syncinfo->si_re;
3311                         if ( re ) {
3312                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
3313                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3314                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
3315                         }
3316                         syncinfo_free( c->be->be_syncinfo );
3317                         c->be->be_syncinfo = NULL;
3318                 }
3319                 SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
3320                 return 0;
3321         }
3322         if ( SLAP_SHADOW( c->be ) ) {
3323                 Debug(LDAP_DEBUG_ANY, "%s: "
3324                         "syncrepl: database already shadowed.\n",
3325                         c->log, 0, 0);
3326                 return(1);
3327         } else if ( add_syncrepl( c ) ) {
3328                 return(1);
3329         }
3330         return config_sync_shadow( c );
3331 }