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