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