]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
psearch consistency patch for releng
[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-2004 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 "ldap_pvt.h"
27 #include "lutil.h"
28 #include "slap.h"
29 #include "lutil_ldap.h"
30
31 #include "ldap_rq.h"
32
33 #define SYNCREPL_STR    "syncreplxxx"
34 #define CN_STR  "cn="
35
36 static const struct berval slap_syncrepl_bvc = BER_BVC(SYNCREPL_STR);
37 static const struct berval slap_syncrepl_cn_bvc = BER_BVC(CN_STR SYNCREPL_STR);
38
39 static int syncuuid_cmp( const void *, const void * );
40 static void avl_ber_bvfree( void * );
41 static void syncrepl_del_nonpresent( Operation *, syncinfo_t * );
42
43 /* callback functions */
44 static int dn_callback( struct slap_op *, struct slap_rep * );
45 static int nonpresent_callback( struct slap_op *, struct slap_rep * );
46 static int null_callback( struct slap_op *, struct slap_rep * );
47
48 static int si_refreshDelete = 0;
49 static int si_refreshPresent = 0;
50
51 static AttributeDescription *sync_descs[4];
52
53 struct runqueue_s syncrepl_rq;
54
55 void
56 init_syncrepl(syncinfo_t *si)
57 {
58         int i, j, k, n;
59         char **tmp;
60
61         if ( !sync_descs[0] ) {
62                 sync_descs[0] = slap_schema.si_ad_objectClass;
63                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
64                 sync_descs[2] = slap_schema.si_ad_entryCSN;
65                 sync_descs[3] = NULL;
66         }
67
68         for ( n = 0; si->si_attrs[ n ] != NULL; n++ ) /* empty */;
69
70         if ( n ) {
71                 /* Delete Attributes */
72                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
73                         for ( j = 0; si->si_attrs[j] != NULL; j++ ) {
74                                 if ( strcmp( si->si_attrs[j], sync_descs[i]->ad_cname.bv_val )
75                                         == 0 )
76                                 {
77                                         ch_free( si->si_attrs[j] );
78                                         for ( k = j; si->si_attrs[k] != NULL; k++ ) {
79                                                 si->si_attrs[k] = si->si_attrs[k+1];
80                                         }
81                                 }
82                         }
83                 }
84                 for ( n = 0; si->si_attrs[ n ] != NULL; n++ ) /* empty */;
85                 tmp = ( char ** ) ch_realloc( si->si_attrs, (n + 4)*sizeof( char * ));
86                 if ( tmp == NULL ) {
87 #ifdef NEW_LOGGING
88                         LDAP_LOG( OPERATION, ERR, "out of memory\n", 0,0,0 );
89 #else
90                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
91 #endif
92                 }
93
94                 /* Add Attributes */
95                 for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
96                         tmp[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
97                         tmp[ n ] = NULL;
98                 }
99
100         } else {
101                 tmp = ( char ** ) ch_realloc( si->si_attrs, 3 * sizeof( char * ));
102                 if ( tmp == NULL ) {
103 #ifdef NEW_LOGGING
104                         LDAP_LOG( OPERATION, ERR, "out of memory\n", 0,0,0 );
105 #else
106                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
107 #endif
108                 }
109                 tmp[ n++ ] = ch_strdup( "*" );
110                 tmp[ n++ ] = ch_strdup( "+" );
111                 tmp[ n ] = NULL;
112         }
113         
114         si->si_attrs = tmp;
115
116         for ( n = 0; si->si_exattrs[ n ] != NULL; n++ ) /* empty */;
117         if ( n ) {
118                 /* Delete Attributes from exattrs list */
119                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
120                         for ( j = 0; si->si_exattrs[j] != NULL; j++ ) {
121                                 if ( strcmp( si->si_exattrs[j], sync_descs[i]->ad_cname.bv_val )
122                                         == 0 )
123                                 {
124                                         ch_free( si->si_exattrs[j] );
125                                         for ( k = j; si->si_exattrs[k] != NULL; k++ ) {
126                                                 si->si_exattrs[k] = si->si_exattrs[k+1];
127                                         }
128                                 }
129                         }
130                 }
131         }
132 }
133
134 static int
135 ldap_sync_search(
136         syncinfo_t *si,
137         void *ctx
138 )
139 {
140         BerElementBuffer berbuf;
141         BerElement *ber = (BerElement *)&berbuf;
142         LDAPControl c[2], *ctrls[3];
143         struct timeval timeout;
144         ber_int_t       msgid;
145         int rc;
146
147         /* setup LDAP SYNC control */
148         ber_init2( ber, NULL, LBER_USE_DER );
149         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
150
151         if ( si->si_syncCookie.octet_str &&
152                  si->si_syncCookie.octet_str[0].bv_val ) {
153                 ber_printf( ber, "{eO}", abs(si->si_type),
154                                         &si->si_syncCookie.octet_str[0] );
155         } else {
156                 ber_printf( ber, "{e}", abs(si->si_type) );
157         }
158
159         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 )) == LBER_ERROR ) {
160                 ber_free_buf( ber );
161                 return rc;
162         }
163
164         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
165         c[0].ldctl_iscritical = si->si_type < 0;
166         ctrls[0] = &c[0];
167
168         if ( si->si_authzId ) {
169                 c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
170                 ber_str2bv( si->si_authzId, 0, 0, &c[1].ldctl_value );
171                 c[1].ldctl_iscritical = 1;
172                 ctrls[1] = &c[1];
173                 ctrls[2] = NULL;
174         } else {
175                 ctrls[1] = NULL;
176         }
177
178         timeout.tv_sec = si->si_tlimit;
179         timeout.tv_usec = 0;
180
181         rc = ldap_search_ext( si->si_ld, si->si_base.bv_val, si->si_scope,
182                 si->si_filterstr.bv_val, si->si_attrs, si->si_attrsonly,
183                 ctrls, NULL, si->si_tlimit > 0 ? &timeout : NULL,
184                 si->si_slimit, &msgid );
185         ber_free_buf( ber );
186
187         return rc;
188 }
189
190 static int
191 do_syncrep1(
192         Operation *op,
193         syncinfo_t *si )
194 {
195         int     rc;
196         int cmdline_cookie_found = 0;
197
198         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
199         struct berval syncrepl_cn_bv;
200         struct sync_cookie      *sc = NULL;
201         struct sync_cookie      syncCookie = { NULL, -1, NULL };
202         struct berval   *psub;
203 #ifdef HAVE_TLS
204         void    *ssl;
205 #endif
206
207         psub = &si->si_be->be_nsuffix[0];
208
209         /* Init connection to master */
210
211         rc = ldap_initialize( &si->si_ld, si->si_provideruri );
212         if ( rc != LDAP_SUCCESS ) {
213 #ifdef NEW_LOGGING
214                 LDAP_LOG( OPERATION, ERR,
215                         "do_syncrep1: ldap_initialize failed (%s)\n",
216                         si->si_provideruri, 0, 0 );
217 #else
218                 Debug( LDAP_DEBUG_ANY,
219                         "do_syncrep1: ldap_initialize failed (%s)\n",
220                         si->si_provideruri, 0, 0 );
221 #endif
222                 return rc;
223         }
224
225         op->o_protocol = LDAP_VERSION3;
226         ldap_set_option( si->si_ld, LDAP_OPT_PROTOCOL_VERSION, &op->o_protocol );
227
228         /* Bind to master */
229
230         if ( si->si_tls ) {
231                 rc = ldap_start_tls_s( si->si_ld, NULL, NULL );
232                 if( rc != LDAP_SUCCESS ) {
233 #ifdef NEW_LOGGING
234                         LDAP_LOG ( OPERATION, ERR, "do_syncrep1: "
235                                 "%s: ldap_start_tls failed (%d)\n",
236                                 si->si_tls == SYNCINFO_TLS_CRITICAL ? "Error" : "Warning",
237                                 rc, 0 );
238 #else
239                         Debug( LDAP_DEBUG_ANY,
240                                 "%s: ldap_start_tls failed (%d)\n",
241                                 si->si_tls == SYNCINFO_TLS_CRITICAL ? "Error" : "Warning",
242                                 rc, 0 );
243 #endif
244                         if( si->si_tls == SYNCINFO_TLS_CRITICAL ) goto done;
245                 }
246         }
247
248         if ( si->si_bindmethod == LDAP_AUTH_SASL ) {
249 #ifdef HAVE_CYRUS_SASL
250                 void *defaults;
251
252                 if ( si->si_secprops != NULL ) {
253                         rc = ldap_set_option( si->si_ld,
254                                 LDAP_OPT_X_SASL_SECPROPS, si->si_secprops);
255
256                         if( rc != LDAP_OPT_SUCCESS ) {
257 #ifdef NEW_LOGGING
258                                 LDAP_LOG ( OPERATION, ERR, "do_bind: Error: "
259                                         "ldap_set_option(%s,SECPROPS,\"%s\") failed!\n",
260                                         si->si_provideruri, si->si_secprops, 0 );
261 #else
262                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
263                                         "(%s,SECPROPS,\"%s\") failed!\n",
264                                         si->si_provideruri, si->si_secprops, 0 );
265 #endif
266                                 goto done;
267                         }
268                 }
269
270                 defaults = lutil_sasl_defaults( si->si_ld,
271                         si->si_saslmech, si->si_realm,
272                         si->si_authcId, si->si_passwd, si->si_authzId );
273
274                 rc = ldap_sasl_interactive_bind_s( si->si_ld,
275                                 si->si_binddn,
276                                 si->si_saslmech,
277                                 NULL, NULL,
278                                 LDAP_SASL_QUIET,
279                                 lutil_sasl_interact,
280                                 defaults );
281
282                 lutil_sasl_freedefs( defaults );
283
284                 /* FIXME: different error behaviors according to
285                  *      1) return code
286                  *      2) on err policy : exit, retry, backoff ...
287                  */
288                 if ( rc != LDAP_SUCCESS ) {
289 #ifdef NEW_LOGGING
290                         LDAP_LOG ( OPERATION, ERR, "do_syncrep1: "
291                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
292                                 rc, 0, 0 );
293 #else
294                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
295                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
296                                 rc, 0, 0 );
297 #endif
298
299                         /* FIXME (see above comment) */
300                         /* if Kerberos credentials cache is not active, retry */
301                         if ( strcmp( si->si_saslmech, "GSSAPI" ) == 0 &&
302                                 rc == LDAP_LOCAL_ERROR )
303                         {
304                                 rc = LDAP_SERVER_DOWN;
305                         }
306
307                         goto done;
308                 }
309 #else /* HAVE_CYRUS_SASL */
310                 /* Should never get here, we trapped this at config time */
311                 fprintf( stderr, "not compiled with SASL support\n" );
312                 rc = LDAP_OTHER;
313                 goto done;
314 #endif
315         } else {
316                 rc = ldap_bind_s( si->si_ld,
317                         si->si_binddn, si->si_passwd, si->si_bindmethod );
318                 if ( rc != LDAP_SUCCESS ) {
319 #ifdef NEW_LOGGING
320                         LDAP_LOG ( OPERATION, ERR, "do_syncrep1: "
321                                 "ldap_bind_s failed (%d)\n", rc, 0, 0 );
322 #else
323                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
324                                 "ldap_bind_s failed (%d)\n", rc, 0, 0 );
325 #endif
326                         goto done;
327                 }
328         }
329
330         /* Set SSF to strongest of TLS, SASL SSFs */
331         op->o_sasl_ssf = 0;
332         op->o_tls_ssf = 0;
333         op->o_transport_ssf = 0;
334 #ifdef HAVE_TLS
335         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
336                 == LDAP_SUCCESS && ssl != NULL )
337         {
338                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
339         }
340 #endif /* HAVE_TLS */
341         ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &op->o_sasl_ssf );
342         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
343                 ?  op->o_sasl_ssf : op->o_tls_ssf;
344
345         /* get syncrepl cookie of shadow replica from subentry */
346
347         assert( si->si_rid < 1000 );
348         syncrepl_cn_bv.bv_val = syncrepl_cbuf;
349         syncrepl_cn_bv.bv_len = snprintf(syncrepl_cbuf, sizeof(syncrepl_cbuf),
350                 CN_STR "syncrepl%ld", si->si_rid );
351         build_new_dn( &op->o_req_ndn, psub, &syncrepl_cn_bv, op->o_tmpmemctx );
352         op->o_req_dn = op->o_req_ndn;
353
354         LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
355                 if ( si->si_rid == sc->rid ) {
356                         cmdline_cookie_found = 1;
357                         break;
358                 }
359         }
360
361         if ( cmdline_cookie_found ) {
362                 /* cookie is supplied in the command line */
363                 BerVarray cookie = NULL;
364                 struct berval cookie_bv;
365
366                 LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
367                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
368
369                 /* read stored cookie if it exists */
370                 backend_attribute( op, NULL, &op->o_req_ndn,
371                         slap_schema.si_ad_syncreplCookie, &cookie, ACL_READ );
372
373                 if ( !cookie ) {
374                         /* no stored cookie */
375                         if ( sc->ctxcsn == NULL ||
376                                  sc->ctxcsn->bv_val == NULL ) {
377                                 /* if cmdline cookie does not have ctxcsn */
378                                 /* component, set it to an initial value */
379                                 slap_init_sync_cookie_ctxcsn( sc );
380                         }
381                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
382                         slap_sync_cookie_free( sc, 1 );
383                         sc = NULL;
384                 } else {
385                         /* stored cookie */
386                         struct berval newcookie = BER_BVNULL;
387                         ber_dupbv( &cookie_bv, &cookie[0] );
388                         ber_bvarray_add( &si->si_syncCookie.octet_str, &cookie_bv );
389                         slap_parse_sync_cookie( &si->si_syncCookie );
390                         ber_bvarray_free( si->si_syncCookie.octet_str );
391                         si->si_syncCookie.octet_str = NULL;
392                         ber_bvarray_free_x( cookie, op->o_tmpmemctx );
393                         if ( sc->sid != -1 ) {
394                                 /* command line cookie wins */
395                                 si->si_syncCookie.sid = sc->sid;
396                         }
397                         if ( sc->ctxcsn != NULL ) {
398                                 /* command line cookie wins */
399                                 if ( si->si_syncCookie.ctxcsn ) {
400                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
401                                         si->si_syncCookie.ctxcsn = NULL;
402                                 }
403                                 ber_dupbv( &cookie_bv, &sc->ctxcsn[0] );
404                                 ber_bvarray_add( &si->si_syncCookie.ctxcsn, &cookie_bv );
405                         }
406                         if ( sc->rid != -1 ) {
407                                 /* command line cookie wins */
408                                 si->si_syncCookie.rid = sc->rid;
409                         }
410                         slap_sync_cookie_free( sc, 1 );
411                         sc = NULL;
412                         slap_compose_sync_cookie( NULL, &newcookie,
413                                         &si->si_syncCookie.ctxcsn[0],
414                                         si->si_syncCookie.sid, si->si_syncCookie.rid );
415                         ber_bvarray_add( &si->si_syncCookie.octet_str, &newcookie );
416                 }
417         } else {
418                 /* no command line cookie is specified */
419                 if ( si->si_syncCookie.octet_str == NULL ) {
420                         BerVarray cookie = NULL;
421                         struct berval cookie_bv;
422                         /* try to read stored cookie */
423                         backend_attribute( op, NULL, &op->o_req_ndn,
424                                 slap_schema.si_ad_syncreplCookie, &cookie, ACL_READ );
425                         if ( cookie ) {
426                                 ber_dupbv( &cookie_bv, &cookie[0] );
427                                 ber_bvarray_add( &si->si_syncCookie.octet_str, &cookie_bv );
428                                 slap_parse_sync_cookie( &si->si_syncCookie );
429                                 ber_bvarray_free_x( cookie, op->o_tmpmemctx );
430                         }
431                 }
432         }
433
434         rc = ldap_sync_search( si, op->o_tmpmemctx );
435
436         if( rc != LDAP_SUCCESS ) {
437 #ifdef NEW_LOGGING
438                 LDAP_LOG ( OPERATION, ERR, "do_syncrep1: "
439                         "ldap_search_ext: %s (%d)\n", ldap_err2string( rc ), rc, 0 );
440 #else
441                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
442                         "ldap_search_ext: %s (%d)\n", ldap_err2string( rc ), rc, 0 );
443 #endif
444         }
445
446 done:
447         if ( rc ) {
448                 if ( si->si_ld ) {
449                         ldap_unbind( si->si_ld );
450                         si->si_ld = NULL;
451                 }
452         }
453
454         slap_sl_free( op->o_req_ndn.bv_val, op->o_tmpmemctx );
455
456         return rc;
457 }
458
459 static int
460 do_syncrep2(
461         Operation *op,
462         syncinfo_t *si )
463 {
464         LDAPControl     **rctrls = NULL;
465         LDAPControl     *rctrlp;
466
467         BerElementBuffer berbuf;
468         BerElement      *ber = (BerElement *)&berbuf;
469
470         LDAPMessage     *res = NULL;
471         LDAPMessage     *msg = NULL;
472
473         char            *retoid = NULL;
474         struct berval   *retdata = NULL;
475
476         Entry           *entry = NULL;
477
478         int             syncstate;
479         struct berval   syncUUID = BER_BVNULL;
480         struct sync_cookie      syncCookie = { NULL, -1, NULL };
481         struct sync_cookie      syncCookie_req = { NULL, -1, NULL };
482         struct berval           cookie = BER_BVNULL;
483
484         int     rc, err, i;
485         ber_len_t       len;
486
487         int rc_efree = 1;
488
489         struct berval   *psub;
490         Modifications   *modlist = NULL;
491
492         const char              *text;
493         int                             match;
494
495         struct timeval *tout_p = NULL;
496         struct timeval tout = { 0, 0 };
497
498         int             refreshDeletes = 0;
499         int             refreshDone = 1;
500         BerVarray syncUUIDs = NULL;
501         ber_tag_t si_tag;
502
503         if ( slapd_shutdown ) {
504                 rc = -2;
505                 goto done;
506         }
507
508         ber_init2( ber, NULL, LBER_USE_DER );
509         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
510
511 #ifdef NEW_LOGGING
512         LDAP_LOG ( OPERATION, DETAIL1, "do_syncrep2\n", 0, 0, 0 );
513 #else
514         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2\n", 0, 0, 0 );
515 #endif
516
517         psub = &si->si_be->be_nsuffix[0];
518
519         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
520
521         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ){
522                 tout_p = &tout;
523         } else {
524                 tout_p = NULL;
525         }
526
527         while (( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE, tout_p, &res ))
528                 > 0 )
529         {
530                 if ( slapd_shutdown ) {
531                         rc = -2;
532                         goto done;
533                 }
534                 for( msg = ldap_first_message( si->si_ld, res );
535                   msg != NULL;
536                   msg = ldap_next_message( si->si_ld, msg ) )
537                 {
538                         switch( ldap_msgtype( msg ) ) {
539                         case LDAP_RES_SEARCH_ENTRY:
540                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
541                                 /* we can't work without the control */
542                                 if ( !rctrls ) {
543                                         rc = -1;
544                                         goto done;
545                                 }
546                                 rctrlp = *rctrls;
547                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
548                                 ber_scanf( ber, "{em", &syncstate, &syncUUID );
549                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
550                                         ber_scanf( ber, "m}", &cookie );
551                                         if ( cookie.bv_val ) {
552                                                 struct berval tmp_bv;
553                                                 ber_dupbv( &tmp_bv, &cookie );
554                                                 ber_bvarray_add( &syncCookie.octet_str, &tmp_bv );
555                                         }
556                                         if ( syncCookie.octet_str &&
557                                                         syncCookie.octet_str[0].bv_val )
558                                                 slap_parse_sync_cookie( &syncCookie );
559                                 }
560                                 if ( syncrepl_message_to_entry( si, op, msg,
561                                         &modlist, &entry, syncstate ) == LDAP_SUCCESS ) {
562                                         rc_efree = syncrepl_entry( si, op, entry, modlist,
563                                                                 syncstate, &syncUUID, &syncCookie_req );
564                                         if ( syncCookie.octet_str &&
565                                                  syncCookie.octet_str[0].bv_val ) {
566                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
567                                         }
568                                 }
569                                 ldap_controls_free( rctrls );
570                                 if ( modlist ) {
571                                         slap_mods_free( modlist );
572                                 }
573                                 if ( rc_efree && entry ) {
574                                         entry_free( entry );
575                                 }
576                                 entry = NULL;
577                                 break;
578
579                         case LDAP_RES_SEARCH_REFERENCE:
580 #ifdef NEW_LOGGING
581                                 LDAP_LOG( OPERATION, ERR,
582                                         "do_syncrep2: reference received error\n", 0, 0, 0 );
583 #else
584                                 Debug( LDAP_DEBUG_ANY,
585                                         "do_syncrep2: reference received error\n", 0, 0, 0 );
586 #endif
587                                 break;
588
589                         case LDAP_RES_SEARCH_RESULT:
590                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
591                                         &rctrls, 0 );
592                                 if ( rctrls ) {
593                                         rctrlp = *rctrls;
594                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
595
596                                         ber_scanf( ber, "{" /*"}"*/);
597                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
598                                         {
599                                                 ber_scanf( ber, "m", &cookie );
600                                                 if ( cookie.bv_val ) {
601                                                         struct berval tmp_bv;
602                                                         ber_dupbv( &tmp_bv, &cookie );
603                                                         ber_bvarray_add( &syncCookie.octet_str, &tmp_bv);
604                                                 }
605                                                 if ( syncCookie.octet_str &&
606                                                                  syncCookie.octet_str[0].bv_val )
607                                                         slap_parse_sync_cookie( &syncCookie );
608                                         }
609                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
610                                         {
611                                                 ber_scanf( ber, "b", &refreshDeletes );
612                                         }
613                                         ber_scanf( ber, "}" );
614                                 }
615                                 if ( syncCookie_req.ctxcsn == NULL ) {
616                                         match = -1;
617                                 } else if ( syncCookie.ctxcsn == NULL ) {
618                                         match = 1;
619                                 } else {
620                                         value_match( &match, slap_schema.si_ad_entryCSN,
621                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
622                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
623                                                 &syncCookie_req.ctxcsn[0], &syncCookie.ctxcsn[0], &text );
624                                 }
625                                 if ( syncCookie.octet_str && syncCookie.octet_str->bv_val
626                                          && match < 0 && err == LDAP_SUCCESS ) {
627                                         syncrepl_updateCookie( si, op, psub, &syncCookie );
628                                 }
629                                 if ( rctrls ) {
630                                         ldap_controls_free( rctrls );
631                                 }
632                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
633                                         /* FIXME : different error behaviors according to
634                                          *      1) err code : LDAP_BUSY ...
635                                          *      2) on err policy : stop service, stop sync, retry
636                                          */
637                                         if ( refreshDeletes == 0 && match < 0 &&
638                                                  err == LDAP_SUCCESS ) {
639                                                 syncrepl_del_nonpresent( op, si );
640                                         } else {
641                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
642                                                 si->si_presentlist = NULL;
643                                         }
644                                 }
645                                 rc = -2;
646                                 goto done;
647                                 break;
648
649                         case LDAP_RES_INTERMEDIATE:
650                                 rc = ldap_parse_intermediate( si->si_ld, msg,
651                                         &retoid, &retdata, NULL, 0 );
652                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
653                                         ber_init2( ber, retdata, LBER_USE_DER );
654
655                                         switch ( si_tag = ber_peek_tag( ber, &len )) {
656                                         ber_tag_t tag;
657                                         case LDAP_TAG_SYNC_NEW_COOKIE:
658                                                 ber_scanf( ber, "tm", &tag, &cookie );
659                                                 break;
660                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
661                                                 si_refreshDelete = 1;
662                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
663                                                 si_refreshPresent = 1;
664                                                 si_refreshPresent = 1;
665                                                 ber_scanf( ber, "t{", &tag );
666                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
667                                                 {
668                                                         ber_scanf( ber, "m", &cookie );
669                                                         if ( cookie.bv_val ) {
670                                                                 struct berval tmp_bv;
671                                                                 ber_dupbv( &tmp_bv, &cookie );
672                                                                 ber_bvarray_add( &syncCookie.octet_str, &tmp_bv);
673                                                         }
674                                                         if ( syncCookie.octet_str &&
675                                                                          syncCookie.octet_str[0].bv_val )
676                                                                 slap_parse_sync_cookie( &syncCookie );
677                                                 }
678                                                 if ( ber_peek_tag( ber, &len ) ==
679                                                                         LDAP_TAG_REFRESHDONE )
680                                                 {
681                                                         ber_scanf( ber, "b", &refreshDone );
682                                                 }
683                                                 ber_scanf( ber, "}" );
684                                                 break;
685                                         case LDAP_TAG_SYNC_ID_SET:
686                                                 ber_scanf( ber, "t{", &tag );
687                                                 if ( ber_peek_tag( ber, &len ) ==
688                                                                 LDAP_TAG_SYNC_COOKIE ) {
689                                                         ber_scanf( ber, "m", &cookie );
690                                                         if ( cookie.bv_val ) {
691                                                                 struct berval tmp_bv;
692                                                                 ber_dupbv( &tmp_bv, &cookie );
693                                                                 ber_bvarray_add( &syncCookie.octet_str,
694                                                                                                  &tmp_bv );
695                                                         }
696                                                         if ( syncCookie.octet_str &&
697                                                                          syncCookie.octet_str[0].bv_val )
698                                                                 slap_parse_sync_cookie( &syncCookie );
699                                                 }
700                                                 if ( ber_peek_tag( ber, &len ) ==
701                                                                         LDAP_TAG_REFRESHDELETES )
702                                                 {
703                                                         ber_scanf( ber, "b", &refreshDeletes );
704                                                 }
705                                                 ber_scanf( ber, "[W]", &syncUUIDs );
706                                                 ber_scanf( ber, "}" );
707                                                 for ( i = 0; syncUUIDs[i].bv_val; i++ ) {
708                                                         struct berval *syncuuid_bv;
709                                                         syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
710                                                         slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
711                                                         avl_insert( &si->si_presentlist,
712                                                                         (caddr_t) syncuuid_bv,
713                                                                         syncuuid_cmp, avl_dup_error );
714                                                 }
715                                                 slap_sl_free( syncUUIDs, op->o_tmpmemctx );
716                                                 break;
717                                         default:
718 #ifdef NEW_LOGGING
719                                         LDAP_LOG( OPERATION, ERR,
720                                                 "do_syncrep2 : unknown syncinfo tag (%ld)\n",
721                                                 (long) si_tag, 0, 0 );
722 #else
723                                         Debug( LDAP_DEBUG_ANY,
724                                                 "do_syncrep2 : unknown syncinfo tag (%ld)\n",
725                                                 (long) si_tag, 0, 0 );
726 #endif
727                                                 ldap_memfree( retoid );
728                                                 ber_bvfree( retdata );
729                                                 continue;
730                                         }
731
732                                         if ( syncCookie_req.ctxcsn == NULL ) {
733                                                 match = -1;
734                                         } else if ( syncCookie.ctxcsn == NULL ) {
735                                                 match = 1;
736                                         } else {
737                                                 value_match( &match, slap_schema.si_ad_entryCSN,
738                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
739                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
740                                                         &syncCookie_req.ctxcsn[0],
741                                                         &syncCookie.ctxcsn[0], &text );
742                                         }
743
744                                         if ( syncCookie.ctxcsn && syncCookie.ctxcsn[0].bv_val
745                                                  && match < 0 ) {
746                                                 syncrepl_updateCookie( si, op, psub, &syncCookie);
747                                         }
748
749                                         if ( si_refreshPresent == 1 ) {
750                                                 if ( match < 0 ) {
751                                                         syncrepl_del_nonpresent( op, si );
752                                                 }
753                                         } 
754
755                                         ldap_memfree( retoid );
756                                         ber_bvfree( retdata );
757                                         break;
758                                 } else {
759 #ifdef NEW_LOGGING
760                                         LDAP_LOG( OPERATION, ERR,"do_syncrep2 :"
761                                                 " unknown intermediate "
762                                                 "response\n", 0, 0, 0 );
763 #else
764                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
765                                                 "unknown intermediate response (%d)\n",
766                                                 rc, 0, 0 );
767 #endif
768                                         ldap_memfree( retoid );
769                                         ber_bvfree( retdata );
770                                         break;
771                                 }
772                                 break;
773                         default:
774 #ifdef NEW_LOGGING
775                                 LDAP_LOG( OPERATION, ERR, "do_syncrep2 : "
776                                         "unknown message\n", 0, 0, 0 );
777 #else
778                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
779                                         "unknown message\n", 0, 0, 0 );
780 #endif
781                                 break;
782
783                         }
784                         if ( syncCookie.octet_str ) {
785                                 slap_sync_cookie_free( &syncCookie_req, 0 );
786                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
787                                 slap_sync_cookie_free( &syncCookie, 0 );
788                         }
789                 }
790                 ldap_msgfree( res );
791                 res = NULL;
792         }
793
794         if ( rc == -1 ) {
795                 const char *errstr;
796
797                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
798                 errstr = ldap_err2string( rc );
799                 
800 #ifdef NEW_LOGGING
801                 LDAP_LOG( OPERATION, ERR,
802                         "do_syncrep2 : %s\n", errstr, 0, 0 );
803 #else
804                 Debug( LDAP_DEBUG_ANY,
805                         "do_syncrep2 : %s\n", errstr, 0, 0 );
806 #endif
807         }
808
809 done:
810         slap_sync_cookie_free( &syncCookie, 0 );
811         slap_sync_cookie_free( &syncCookie_req, 0 );
812
813         if ( res ) ldap_msgfree( res );
814
815         if ( rc && si->si_ld ) {
816                 ldap_unbind( si->si_ld );
817                 si->si_ld = NULL;
818         }
819
820         return rc;
821 }
822
823 void *
824 do_syncrepl(
825         void    *ctx,
826         void    *arg )
827 {
828         struct re_s* rtask = arg;
829         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
830         Connection conn = {0};
831         Operation op = {0};
832         int rc = LDAP_SUCCESS;
833         int first = 0;
834         int dostop = 0;
835         ber_socket_t s;
836         int i, defer = 1;
837         Backend *be;
838
839 #ifdef NEW_LOGGING
840         LDAP_LOG ( OPERATION, DETAIL1, "do_syncrepl\n", 0, 0, 0 );
841 #else
842         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
843 #endif
844
845         if ( si == NULL )
846                 return NULL;
847
848         switch( abs( si->si_type )) {
849         case LDAP_SYNC_REFRESH_ONLY:
850         case LDAP_SYNC_REFRESH_AND_PERSIST:
851                 break;
852         default:
853                 return NULL;
854         }
855
856         if ( slapd_shutdown && si->si_ld ) {
857                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
858                 connection_client_stop( s );
859                 ldap_unbind( si->si_ld );
860                 si->si_ld = NULL;
861                 return NULL;
862         }
863
864         connection_fake_init( &conn, &op, ctx );
865
866         /* use global malloc for now */
867         op.o_tmpmemctx = NULL;
868         op.o_tmpmfuncs = &ch_mfuncs;
869
870         op.o_dn = si->si_updatedn;
871         op.o_ndn = si->si_updatedn;
872         op.o_managedsait = 1;
873         op.o_bd = be = si->si_be;
874
875         op.o_sync_state.ctxcsn = NULL;
876         op.o_sync_state.sid = -1;
877         op.o_sync_state.octet_str = NULL;
878         op.o_sync_slog_size = -1;
879         LDAP_STAILQ_FIRST( &op.o_sync_slog_list ) = NULL;
880         op.o_sync_slog_list.stqh_last = &LDAP_STAILQ_FIRST(&op.o_sync_slog_list);
881
882         /* Establish session, do search */
883         if ( !si->si_ld ) {
884                 first = 1;
885                 si_refreshDelete = 0;
886                 si_refreshPresent = 0;
887                 rc = do_syncrep1( &op, si );
888         }
889
890         /* Process results */
891         if ( rc == LDAP_SUCCESS ) {
892                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
893
894                 rc = do_syncrep2( &op, si );
895
896                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
897                         /* If we succeeded, enable the connection for further listening.
898                          * If we failed, tear down the connection and reschedule.
899                          */
900                         if ( rc == LDAP_SUCCESS ) {
901                                 if ( first ) {
902                                         rc = connection_client_setup( s, do_syncrepl, arg );
903                                 } else {
904                                         connection_client_enable( s );
905                                 } 
906                         } else if ( !first ) {
907                                 dostop = 1;
908                         }
909                 } else {
910                         if ( rc == -2 ) rc = 0;
911                 }
912         }
913
914         /* At this point, we have 4 cases:
915          * 1) for any hard failure, give up and remove this task
916          * 2) for ServerDown, reschedule this task to run
917          * 3) for Refresh and Success, reschedule to run
918          * 4) for Persist and Success, reschedule to defer
919          */
920         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
921
922         if ( ldap_pvt_runqueue_isrunning( &syncrepl_rq, rtask )) {
923                 ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
924         }
925
926         if ( dostop ) {
927                 connection_client_stop( s );
928         }
929
930         if ( rc == LDAP_SUCCESS ) {
931                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
932                         defer = 0;
933                 }
934                 rtask->interval.tv_sec = si->si_interval;
935                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, defer );
936                 if ( si->si_retrynum ) {
937                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
938                                 si->si_retrynum[i] = si->si_retrynum_init[i];
939                         }
940                         si->si_retrynum[i] = -2;
941                 }
942         } else {
943                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
944                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
945                                 break;
946                 }
947
948                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
949                         ldap_pvt_runqueue_remove( &syncrepl_rq, rtask );
950                         LDAP_STAILQ_REMOVE( &be->be_syncinfo, si, syncinfo_s, si_next );
951                         syncinfo_free( si );
952                 } else if ( si->si_retrynum[i] >= -1 ) {
953                         if ( si->si_retrynum[i] > 0 )
954                                 si->si_retrynum[i]--;
955                         rtask->interval.tv_sec = si->si_retryinterval[i];
956                         ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, 0 );
957                         slap_wake_listener();
958                 }
959         }
960         
961         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
962
963         return NULL;
964 }
965
966 int
967 syncrepl_message_to_entry(
968         syncinfo_t      *si,
969         Operation       *op,
970         LDAPMessage     *msg,
971         Modifications   **modlist,
972         Entry                   **entry,
973         int             syncstate
974 )
975 {
976         Entry           *e = NULL;
977         BerElement      *ber = NULL;
978         Modifications   tmp;
979         Modifications   *mod;
980         Modifications   **modtail = modlist;
981
982         const char      *text;
983         char txtbuf[SLAP_TEXT_BUFLEN];
984         size_t textlen = sizeof txtbuf;
985
986         struct berval   bdn = {0, NULL}, dn, ndn;
987         int             rc;
988
989         *modlist = NULL;
990
991         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
992 #ifdef NEW_LOGGING
993                 LDAP_LOG( OPERATION, ERR,
994                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
995 #else
996                 Debug( LDAP_DEBUG_ANY,
997                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
998 #endif
999                 return -1;
1000         }
1001
1002         op->o_tag = LDAP_REQ_ADD;
1003
1004         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1005
1006         if ( rc != LDAP_SUCCESS ) {
1007 #ifdef NEW_LOGGING
1008                 LDAP_LOG( OPERATION, ERR,
1009                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1010 #else
1011                 Debug( LDAP_DEBUG_ANY,
1012                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1013 #endif
1014                 return rc;
1015         }
1016
1017         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1018         ber_dupbv( &op->o_req_dn, &dn );
1019         ber_dupbv( &op->o_req_ndn, &ndn );
1020         sl_free( ndn.bv_val, op->o_tmpmemctx );
1021         sl_free( dn.bv_val, op->o_tmpmemctx );
1022
1023         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1024                 if ( entry )
1025                         *entry = NULL;
1026                 return LDAP_SUCCESS;
1027         }
1028
1029         if ( entry == NULL ) {
1030                 return -1;
1031         }
1032
1033         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1034         *entry = e;
1035         e->e_name = op->o_req_dn;
1036         e->e_nname = op->o_req_ndn;
1037
1038         while ( ber_remaining( ber ) ) {
1039                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1040                         LBER_ERROR ) || ( tmp.sml_type.bv_val == NULL ))
1041                 {
1042                         break;
1043                 }
1044
1045                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1046
1047                 mod->sml_op = LDAP_MOD_REPLACE;
1048                 mod->sml_next = NULL;
1049                 mod->sml_desc = NULL;
1050                 mod->sml_type = tmp.sml_type;
1051                 mod->sml_values = tmp.sml_values;
1052                 mod->sml_nvalues = NULL;
1053
1054                 *modtail = mod;
1055                 modtail = &mod->sml_next;
1056         }
1057
1058         if ( *modlist == NULL ) {
1059 #ifdef NEW_LOGGING
1060                 LDAP_LOG( OPERATION, ERR,
1061                                 "syncrepl_message_to_entry: no attributes\n", 0, 0, 0 );
1062 #else
1063                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1064                                 0, 0, 0 );
1065 #endif
1066                 rc = -1;
1067                 goto done;
1068         }
1069
1070         rc = slap_mods_check( *modlist, 1, &text, txtbuf, textlen, NULL );
1071
1072         if ( rc != LDAP_SUCCESS ) {
1073 #ifdef NEW_LOGGING
1074                 LDAP_LOG( OPERATION, ERR,
1075                                 "syncrepl_message_to_entry: mods check (%s)\n", text, 0, 0 );
1076 #else
1077                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1078                                 text, 0, 0 );
1079 #endif
1080                 goto done;
1081         }
1082
1083         /* Strip out dynamically generated attrs */
1084         for ( modtail = modlist; *modtail ; ) {
1085                 mod = *modtail;
1086                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1087                         *modtail = mod->sml_next;
1088                         slap_mod_free( &mod->sml_mod, 0 );
1089                         ch_free( mod );
1090                 } else {
1091                         modtail = &mod->sml_next;
1092                 }
1093         }
1094
1095         /* Strip out attrs in exattrs list */
1096         for ( modtail = modlist; *modtail ; ) {
1097                 mod = *modtail;
1098                 if ( ldap_charray_inlist( si->si_exattrs,
1099                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1100                         *modtail = mod->sml_next;
1101                         slap_mod_free( &mod->sml_mod, 0 );
1102                         ch_free( mod );
1103                 } else {
1104                         modtail = &mod->sml_next;
1105                 }
1106         }
1107         
1108         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1109         if( rc != LDAP_SUCCESS ) {
1110 #ifdef NEW_LOGGING
1111                 LDAP_LOG( OPERATION, ERR,
1112                                 "syncrepl_message_to_entry: mods2entry (%s)\n", text, 0, 0 );
1113 #else
1114                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1115                                 text, 0, 0 );
1116 #endif
1117         }
1118
1119 done:
1120         ber_free ( ber, 0 );
1121         if ( rc != LDAP_SUCCESS ) {
1122                 if ( e ) {
1123                         entry_free( e );
1124                         *entry = e = NULL;
1125                 }
1126         }
1127
1128         return rc;
1129 }
1130
1131 int
1132 syncrepl_entry(
1133         syncinfo_t* si,
1134         Operation *op,
1135         Entry* entry,
1136         Modifications* modlist,
1137         int syncstate,
1138         struct berval* syncUUID,
1139         struct sync_cookie* syncCookie_req
1140 )
1141 {
1142         Backend *be = op->o_bd;
1143         slap_callback   cb = { NULL };
1144         struct berval   *syncuuid_bv = NULL;
1145         struct berval   syncUUID_strrep = BER_BVNULL;
1146         struct berval   uuid_bv = BER_BVNULL;
1147
1148         SlapReply       rs_search = {REP_RESULT};
1149         SlapReply       rs_delete = {REP_RESULT};
1150         SlapReply       rs_add = {REP_RESULT};
1151         SlapReply       rs_modify = {REP_RESULT};
1152         Filter f = {0};
1153         AttributeAssertion ava = {0};
1154         int rc = LDAP_SUCCESS;
1155         int ret = LDAP_SUCCESS;
1156         const char *text;
1157
1158         struct berval pdn = BER_BVNULL;
1159         struct berval org_req_dn = BER_BVNULL;
1160         struct berval org_req_ndn = BER_BVNULL;
1161         struct berval org_dn = BER_BVNULL;
1162         struct berval org_ndn = BER_BVNULL;
1163         int     org_managedsait;
1164
1165         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ))
1166         {
1167                 if (!si_refreshPresent) {
1168                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1169                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1170                                 syncuuid_cmp, avl_dup_error );
1171                 }
1172         }
1173
1174         if ( syncstate == LDAP_SYNC_PRESENT ) {
1175                 return 0;
1176         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1177                 if ( entry == NULL ) {
1178                         return 0;
1179                 }
1180         }
1181
1182         f.f_choice = LDAP_FILTER_EQUALITY;
1183         f.f_ava = &ava;
1184         ava.aa_desc = slap_schema.si_ad_entryUUID;
1185         slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1186         ava.aa_value = *syncUUID;
1187         op->ors_filter = &f;
1188
1189         op->ors_filterstr.bv_len = (sizeof("entryUUID=")-1) + syncUUID->bv_len;
1190         op->ors_filterstr.bv_val = (char *) sl_malloc(
1191                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1192         AC_MEMCPY( op->ors_filterstr.bv_val, "entryUUID=", sizeof("entryUUID=")-1 );
1193         AC_MEMCPY( &op->ors_filterstr.bv_val[sizeof("entryUUID=")-1],
1194                 syncUUID->bv_val, syncUUID->bv_len );
1195         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1196
1197         op->o_tag = LDAP_REQ_SEARCH;
1198         op->ors_scope = LDAP_SCOPE_SUBTREE;
1199
1200         /* get syncrepl cookie of shadow replica from subentry */
1201         op->o_req_dn = si->si_base;
1202         op->o_req_ndn = si->si_base;
1203
1204         op->o_time = slap_get_time();
1205         op->ors_tlimit = SLAP_NO_LIMIT;
1206         op->ors_slimit = 1;
1207
1208         /* set callback function */
1209         op->o_callback = &cb;
1210         cb.sc_response = dn_callback;
1211         cb.sc_private = si;
1212
1213         si->si_syncUUID_ndn.bv_val = NULL;
1214
1215         if ( limits_check( op, &rs_search ) == 0 ) {
1216                 rc = be->be_search( op, &rs_search );
1217         }
1218
1219         if ( op->ors_filterstr.bv_val ) {
1220                 sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1221         }
1222
1223         cb.sc_response = null_callback;
1224         cb.sc_private = si;
1225
1226         if ( rs_search.sr_err == LDAP_SUCCESS && si->si_syncUUID_ndn.bv_val ) {
1227                 char *subseq_ptr;
1228
1229                 if ( syncstate != LDAP_SYNC_DELETE ) {
1230                         op->o_no_psearch = 1;
1231                 }
1232
1233                 ber_dupbv( &op->o_sync_csn, syncCookie_req->ctxcsn );
1234                 if ( op->o_sync_csn.bv_val ) {
1235                         subseq_ptr = strstr( op->o_sync_csn.bv_val, "#0000" );
1236                         subseq_ptr += 4;
1237                         *subseq_ptr = '1';
1238                 }
1239                 
1240                 op->o_req_dn = si->si_syncUUID_ndn;
1241                 op->o_req_ndn = si->si_syncUUID_ndn;
1242                 op->o_tag = LDAP_REQ_DELETE;
1243                 rc = be->be_delete( op, &rs_delete );
1244
1245                 org_req_dn = op->o_req_dn;
1246                 org_req_ndn = op->o_req_ndn;
1247                 org_dn = op->o_dn;
1248                 org_ndn = op->o_ndn;
1249                 org_managedsait = get_manageDSAit( op );
1250                 op->o_dn = op->o_bd->be_rootdn;
1251                 op->o_ndn = op->o_bd->be_rootndn;
1252                 op->o_managedsait = 1;
1253
1254                 while ( rs_delete.sr_err == LDAP_SUCCESS && op->o_delete_glue_parent ) {
1255                         op->o_delete_glue_parent = 0;
1256                         if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1257                                 slap_callback cb = { NULL };
1258                                 cb.sc_response = slap_null_cb;
1259                                 dnParent( &op->o_req_ndn, &pdn );
1260                                 op->o_req_dn = pdn;
1261                                 op->o_req_ndn = pdn;
1262                                 op->o_callback = &cb;
1263                                 op->o_bd->be_delete( op, &rs_delete );
1264                         } else {
1265                                 break;
1266                     }
1267                 }
1268
1269                 op->o_managedsait = org_managedsait;
1270                 op->o_dn = org_dn;
1271                 op->o_ndn = org_ndn;
1272                 op->o_req_dn = org_req_dn;
1273                 op->o_req_ndn = org_req_ndn;
1274                 op->o_delete_glue_parent = 0;
1275
1276                 op->o_no_psearch = 0;
1277         }
1278
1279         switch ( syncstate ) {
1280         case LDAP_SYNC_ADD:
1281         case LDAP_SYNC_MODIFY:
1282                 if ( rs_search.sr_err == LDAP_SUCCESS ||
1283                          rs_search.sr_err == LDAP_REFERRAL ||
1284                          rs_search.sr_err == LDAP_NO_SUCH_OBJECT ||
1285                          rs_search.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF )
1286                 {
1287                         attr_delete( &entry->e_attrs, slap_schema.si_ad_entryUUID );
1288                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1289                                 &syncUUID_strrep, syncUUID );
1290
1291                         op->o_tag = LDAP_REQ_ADD;
1292                         op->ora_e = entry;
1293                         op->o_req_dn = entry->e_name;
1294                         op->o_req_ndn = entry->e_nname;
1295
1296                         rc = be->be_add( op, &rs_add );
1297
1298                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1299                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS &&
1300                                          rs_search.sr_err != LDAP_NO_SUCH_OBJECT ) {
1301                                         Modifications *mod;
1302                                         Modifications *modtail = modlist;
1303
1304                                         assert( modlist );
1305
1306                                         for ( mod = modlist; mod != NULL; mod = mod->sml_next ) {
1307                                                 modtail = mod;
1308                                         }
1309
1310                                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1311                                         ber_dupbv( &uuid_bv, syncUUID );
1312                                         mod->sml_op = LDAP_MOD_REPLACE;
1313                                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1314                                         mod->sml_type = mod->sml_desc->ad_cname;
1315                                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1316                                         modtail->sml_next = mod;
1317                                         
1318                                         op->o_tag = LDAP_REQ_MODIFY;
1319                                         op->orm_modlist = modlist;
1320                                         op->o_req_dn = entry->e_name;
1321                                         op->o_req_ndn = entry->e_nname;
1322
1323                                         rc = be->be_modify( op, &rs_modify );
1324                                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1325 #ifdef NEW_LOGGING
1326                                                 LDAP_LOG( OPERATION, ERR,
1327                                                         "syncrepl_entry : be_modify failed (%d)\n",
1328                                                         rs_modify.sr_err, 0, 0 );
1329 #else
1330                                                 Debug( LDAP_DEBUG_ANY,
1331                                                         "syncrepl_entry : be_modify failed (%d)\n",
1332                                                         rs_modify.sr_err, 0, 0 );
1333 #endif
1334                                         }
1335                                         ret = 1;
1336                                         goto done;
1337                                 } else if ( rs_modify.sr_err == LDAP_REFERRAL ||
1338                                                         rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1339                                         syncrepl_add_glue( op, entry );
1340                                         ret = 0;
1341                                         goto done;
1342                                 } else {
1343 #ifdef NEW_LOGGING
1344                                         LDAP_LOG( OPERATION, ERR,
1345                                                 "syncrepl_entry : be_add failed (%d)\n",
1346                                                 rs_add.sr_err, 0, 0 );
1347 #else
1348                                         Debug( LDAP_DEBUG_ANY,
1349                                                 "syncrepl_entry : be_add failed (%d)\n",
1350                                                 rs_add.sr_err, 0, 0 );
1351 #endif
1352                                         ret = 1;
1353                                         goto done;
1354                                 }
1355                         } else {
1356                                 be_entry_release_w( op, entry );
1357                                 ret = 0;
1358                                 goto done;
1359                         }
1360                 } else {
1361 #ifdef NEW_LOGGING
1362                         LDAP_LOG( OPERATION, ERR,
1363                                 "syncrepl_entry : be_search failed (%d)\n",
1364                                 rs_search.sr_err, 0, 0 );
1365 #else
1366                         Debug( LDAP_DEBUG_ANY,
1367                                 "syncrepl_entry : be_search failed (%d)\n",
1368                                 rs_search.sr_err, 0, 0 );
1369 #endif
1370                         ret = 1;
1371                         goto done;
1372                 }
1373
1374         case LDAP_SYNC_DELETE :
1375                 /* Already deleted */
1376                 ret = 0;
1377                 goto done;
1378
1379         default :
1380 #ifdef NEW_LOGGING
1381                 LDAP_LOG( OPERATION, ERR,
1382                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1383 #else
1384                 Debug( LDAP_DEBUG_ANY,
1385                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1386 #endif
1387                 ret = 1;
1388                 goto done;
1389         }
1390
1391 done :
1392
1393         if ( syncUUID_strrep.bv_val ) {
1394                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1395         }
1396         if ( si->si_syncUUID_ndn.bv_val ) {
1397                 ch_free( si->si_syncUUID_ndn.bv_val );
1398                 si->si_syncUUID_ndn.bv_val = NULL;
1399         }
1400         return ret;
1401 }
1402
1403 static struct berval gcbva[] = {
1404         BER_BVC("top"),
1405         BER_BVC("glue"),
1406         BER_BVNULL
1407 };
1408
1409 static void
1410 syncrepl_del_nonpresent(
1411         Operation *op,
1412         syncinfo_t *si
1413 )
1414 {
1415         Backend* be = op->o_bd;
1416         slap_callback   cb = { NULL };
1417         SlapReply       rs_search = {REP_RESULT};
1418         SlapReply       rs_delete = {REP_RESULT};
1419         SlapReply       rs_modify = {REP_RESULT};
1420         struct nonpresent_entry *np_list, *np_prev;
1421         int rc;
1422         Modifications *ml;
1423         Modifications *mlnext;
1424         Modifications *mod;
1425         Modifications *modlist = NULL;
1426         Modifications **modtail = &modlist;
1427         Attribute       *attr;
1428
1429         struct berval pdn = BER_BVNULL;
1430         struct berval org_req_dn = BER_BVNULL;
1431         struct berval org_req_ndn = BER_BVNULL;
1432         struct berval org_dn = BER_BVNULL;
1433         struct berval org_ndn = BER_BVNULL;
1434         int     org_managedsait;
1435
1436         op->o_req_dn = si->si_base;
1437         op->o_req_ndn = si->si_base;
1438
1439         cb.sc_response = nonpresent_callback;
1440         cb.sc_private = si;
1441
1442         op->o_callback = &cb;
1443         op->o_tag = LDAP_REQ_SEARCH;
1444         op->ors_scope = si->si_scope;
1445         op->ors_deref = LDAP_DEREF_NEVER;
1446         op->o_time = slap_get_time();
1447         op->ors_tlimit = SLAP_NO_LIMIT;
1448         op->ors_slimit = SLAP_NO_LIMIT;
1449         op->ors_attrsonly = 0;
1450         op->ors_attrs = NULL;
1451         op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1452         op->ors_filterstr = si->si_filterstr;
1453
1454         op->o_nocaching = 1;
1455         op->o_managedsait = 0;
1456
1457         if ( limits_check( op, &rs_search ) == 0 ) {
1458                 rc = be->be_search( op, &rs_search );
1459         }
1460
1461         op->o_managedsait = 1;
1462         op->o_nocaching = 0;
1463
1464         if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1465
1466         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1467                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1468                 while ( np_list != NULL ) {
1469                         LDAP_LIST_REMOVE( np_list, npe_link );
1470                         np_prev = np_list;
1471                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1472                         op->o_tag = LDAP_REQ_DELETE;
1473                         op->o_callback = &cb;
1474                         cb.sc_response = null_callback;
1475                         cb.sc_private = si;
1476                         op->o_req_dn = *np_prev->npe_name;
1477                         op->o_req_ndn = *np_prev->npe_nname;
1478                         rc = op->o_bd->be_delete( op, &rs_delete );
1479
1480                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1481                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1482                                 mod->sml_op = LDAP_MOD_REPLACE;
1483                                 mod->sml_desc = slap_schema.si_ad_objectClass;
1484                                 mod->sml_type = mod->sml_desc->ad_cname;
1485                                 mod->sml_values = &gcbva[0];
1486                                 *modtail = mod;
1487                                 modtail = &mod->sml_next;
1488
1489                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1490                                 mod->sml_op = LDAP_MOD_REPLACE;
1491                                 mod->sml_desc = slap_schema.si_ad_structuralObjectClass;
1492                                 mod->sml_type = mod->sml_desc->ad_cname;
1493                                 mod->sml_values = &gcbva[1];
1494                                 *modtail = mod;
1495                                 modtail = &mod->sml_next;
1496
1497                                 op->o_tag = LDAP_REQ_MODIFY;
1498                                 op->orm_modlist = modlist;
1499
1500                                 rc = be->be_modify( op, &rs_modify );
1501
1502                                 for ( ml = modlist; ml != NULL; ml = mlnext ) {
1503                                         mlnext = ml->sml_next;
1504                                         free( ml );
1505                                 }
1506                         }
1507
1508                         org_req_dn = op->o_req_dn;
1509                         org_req_ndn = op->o_req_ndn;
1510                         org_dn = op->o_dn;
1511                         org_ndn = op->o_ndn;
1512                         org_managedsait = get_manageDSAit( op );
1513                         op->o_dn = op->o_bd->be_rootdn;
1514                         op->o_ndn = op->o_bd->be_rootndn;
1515                         op->o_managedsait = 1;
1516
1517                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1518                                         op->o_delete_glue_parent ) {
1519                                 op->o_delete_glue_parent = 0;
1520                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1521                                         slap_callback cb = { NULL };
1522                                         cb.sc_response = slap_null_cb;
1523                                         dnParent( &op->o_req_ndn, &pdn );
1524                                         op->o_req_dn = pdn;
1525                                         op->o_req_ndn = pdn;
1526                                         op->o_callback = &cb;
1527                                         /* give it a root privil ? */
1528                                         op->o_bd->be_delete( op, &rs_delete );
1529                                 } else {
1530                                         break;
1531                             }
1532                         }
1533
1534                         op->o_managedsait = org_managedsait;
1535                         op->o_dn = org_dn;
1536                         op->o_ndn = org_ndn;
1537                         op->o_req_dn = org_req_dn;
1538                         op->o_req_ndn = org_req_ndn;
1539                         op->o_delete_glue_parent = 0;
1540
1541                         ber_bvfree( np_prev->npe_name );
1542                         ber_bvfree( np_prev->npe_nname );
1543                         op->o_req_dn.bv_val = NULL;
1544                         op->o_req_ndn.bv_val = NULL;
1545                         ch_free( np_prev );
1546                 }
1547         }
1548
1549         return;
1550 }
1551
1552
1553 void
1554 syncrepl_add_glue(
1555         Operation* op,
1556         Entry *e
1557 )
1558 {
1559         Backend *be = op->o_bd;
1560         slap_callback cb = { NULL };
1561         Attribute       *a;
1562         int     rc;
1563         int suffrdns;
1564         int i;
1565         struct berval dn = {0, NULL};
1566         struct berval ndn = {0, NULL};
1567         Entry   *glue;
1568         SlapReply       rs_add = {REP_RESULT};
1569         char    *ptr, *comma;
1570
1571         op->o_tag = LDAP_REQ_ADD;
1572         op->o_callback = &cb;
1573         cb.sc_response = null_callback;
1574         cb.sc_private = NULL;
1575
1576         dn = e->e_name;
1577         ndn = e->e_nname;
1578
1579         /* count RDNs in suffix */
1580         if ( be->be_nsuffix[0].bv_len ) {
1581                 for (i=0, ptr=be->be_nsuffix[0].bv_val; ptr; ptr=strchr( ptr, ',' )) {
1582                         ptr++;
1583                         i++;
1584                 }
1585                 suffrdns = i;
1586         } else {
1587                 /* suffix is "" */
1588                 suffrdns = 0;
1589         }
1590
1591         /* Start with BE suffix */
1592         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
1593                 comma = strrchr(dn.bv_val, ',');
1594                 if ( ptr ) *ptr = ',';
1595                 if ( comma ) *comma = '\0';
1596                 ptr = comma;
1597         }
1598         if ( ptr ) {
1599                 *ptr++ = ',';
1600                 dn.bv_len -= ptr - dn.bv_val;
1601                 dn.bv_val = ptr;
1602         }
1603         /* the normalizedDNs are always the same length, no counting
1604          * required.
1605          */
1606         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
1607                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
1608                 ndn.bv_len = be->be_nsuffix[0].bv_len;
1609         }
1610
1611         while ( ndn.bv_val > e->e_nname.bv_val ) {
1612                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
1613                 ber_dupbv( &glue->e_name, &dn );
1614                 ber_dupbv( &glue->e_nname, &ndn );
1615
1616                 a = ch_calloc( 1, sizeof( Attribute ));
1617                 a->a_desc = slap_schema.si_ad_objectClass;
1618
1619                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1620                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
1621                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
1622                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
1623
1624                 a->a_nvals = a->a_vals;
1625
1626                 a->a_next = glue->e_attrs;
1627                 glue->e_attrs = a;
1628
1629                 a = ch_calloc( 1, sizeof( Attribute ));
1630                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1631
1632                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1633                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
1634                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
1635
1636                 a->a_nvals = a->a_vals;
1637
1638                 a->a_next = glue->e_attrs;
1639                 glue->e_attrs = a;
1640
1641                 op->o_req_dn = glue->e_name;
1642                 op->o_req_ndn = glue->e_nname;
1643                 op->ora_e = glue;
1644                 rc = be->be_add ( op, &rs_add );
1645                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
1646                         be_entry_release_w( op, glue );
1647                 } else {
1648                 /* incl. ALREADY EXIST */
1649                         entry_free( glue );
1650                 }
1651
1652                 /* Move to next child */
1653                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
1654                         /* empty */
1655                 }
1656                 if ( ptr == e->e_name.bv_val ) break;
1657                 dn.bv_val = ++ptr;
1658                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
1659                 for( ptr = ndn.bv_val-2;
1660                         ptr > e->e_nname.bv_val && *ptr != ',';
1661                         ptr--)
1662                 {
1663                         /* empty */
1664                 }
1665                 ndn.bv_val = ++ptr;
1666                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
1667         }
1668
1669         op->o_req_dn = e->e_name;
1670         op->o_req_ndn = e->e_nname;
1671         op->ora_e = e;
1672         rc = be->be_add ( op, &rs_add );
1673         if ( rs_add.sr_err == LDAP_SUCCESS ) {
1674                 be_entry_release_w( op, e );
1675         } else {
1676                 entry_free( e );
1677         }
1678
1679         return;
1680 }
1681
1682 static struct berval ocbva[] = {
1683         BER_BVC("top"),
1684         BER_BVC("subentry"),
1685         BER_BVC("syncConsumerSubentry"),
1686         BER_BVNULL
1687 };
1688
1689 static struct berval cnbva[] = {
1690         BER_BVNULL,
1691         BER_BVNULL
1692 };
1693
1694 static struct berval ssbva[] = {
1695         BER_BVC("{}"),
1696         BER_BVNULL
1697 };
1698
1699 static struct berval scbva[] = {
1700         BER_BVNULL,
1701         BER_BVNULL
1702 };
1703
1704 void
1705 syncrepl_updateCookie(
1706         syncinfo_t *si,
1707         Operation *op,
1708         struct berval *pdn,
1709         struct sync_cookie *syncCookie
1710 )
1711 {
1712         Backend *be = op->o_bd;
1713         Modifications *ml;
1714         Modifications *mlnext;
1715         Modifications *mod;
1716         Modifications *modlist = NULL;
1717         Modifications **modtail = &modlist;
1718
1719         const char      *text;
1720         char txtbuf[SLAP_TEXT_BUFLEN];
1721         size_t textlen = sizeof txtbuf;
1722
1723         Entry* e = NULL;
1724         int rc;
1725
1726         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
1727         struct berval slap_syncrepl_dn_bv = BER_BVNULL;
1728         struct berval slap_syncrepl_cn_bv = BER_BVNULL;
1729         
1730         slap_callback cb = { NULL };
1731         SlapReply       rs_add = {REP_RESULT};
1732         SlapReply       rs_modify = {REP_RESULT};
1733
1734         slap_sync_cookie_free( &si->si_syncCookie, 0 );
1735         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
1736
1737         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1738         mod->sml_op = LDAP_MOD_REPLACE;
1739         mod->sml_desc = slap_schema.si_ad_objectClass;
1740         mod->sml_type = mod->sml_desc->ad_cname;
1741         mod->sml_values = ocbva;
1742         *modtail = mod;
1743         modtail = &mod->sml_next;
1744
1745         ber_dupbv( &cnbva[0], (struct berval *) &slap_syncrepl_bvc );
1746         assert( si->si_rid < 1000 );
1747         cnbva[0].bv_len = snprintf( cnbva[0].bv_val,
1748                 slap_syncrepl_bvc.bv_len + 1,
1749                 "syncrepl%ld", si->si_rid );
1750         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1751         mod->sml_op = LDAP_MOD_REPLACE;
1752         mod->sml_desc = slap_schema.si_ad_cn;
1753         mod->sml_type = mod->sml_desc->ad_cname;
1754         mod->sml_values = cnbva;
1755         *modtail = mod;
1756         modtail = &mod->sml_next;
1757
1758         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1759         mod->sml_op = LDAP_MOD_REPLACE;
1760         mod->sml_desc = slap_schema.si_ad_subtreeSpecification;
1761         mod->sml_type = mod->sml_desc->ad_cname;
1762         mod->sml_values = ssbva;
1763         *modtail = mod;
1764         modtail = &mod->sml_next;
1765
1766         /* Keep this last, so we can avoid touching the previous
1767          * attributes unnecessarily.
1768          */
1769         if ( scbva[0].bv_val ) ch_free( scbva[0].bv_val );
1770         ber_dupbv( &scbva[0], &si->si_syncCookie.octet_str[0] );
1771         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1772         mod->sml_op = LDAP_MOD_REPLACE;
1773         mod->sml_desc = slap_schema.si_ad_syncreplCookie;
1774         mod->sml_type = mod->sml_desc->ad_cname;
1775         mod->sml_values = scbva;
1776         *modtail = mod;
1777         modtail = &mod->sml_next;
1778
1779         mlnext = mod;
1780
1781         op->o_tag = LDAP_REQ_ADD;
1782         rc = slap_mods_opattrs( op, modlist, modtail,
1783                  &text, txtbuf, textlen, 0 );
1784
1785         for ( ml = modlist; ml != NULL; ml = ml->sml_next ) {
1786                 ml->sml_op = LDAP_MOD_REPLACE;
1787         }
1788
1789         if( rc != LDAP_SUCCESS ) {
1790 #ifdef NEW_LOGGING
1791                 LDAP_LOG( OPERATION, ERR,
1792                         "syncrepl_updateCookie: mods opattrs (%s)\n", text, 0, 0 );
1793 #else
1794                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1795                          text, 0, 0 );
1796 #endif
1797         }
1798
1799         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1800
1801         slap_syncrepl_cn_bv.bv_val = syncrepl_cbuf;
1802         assert( si->si_rid < 1000 );
1803         slap_syncrepl_cn_bv.bv_len = snprintf( slap_syncrepl_cn_bv.bv_val,
1804                 slap_syncrepl_cn_bvc.bv_len + 1,
1805                 "cn=syncrepl%ld", si->si_rid );
1806
1807         build_new_dn( &slap_syncrepl_dn_bv, pdn, &slap_syncrepl_cn_bv,
1808                 op->o_tmpmemctx );
1809         ber_dupbv( &e->e_name, &slap_syncrepl_dn_bv );
1810         ber_dupbv( &e->e_nname, &slap_syncrepl_dn_bv );
1811
1812         if ( slap_syncrepl_dn_bv.bv_val ) {
1813                 sl_free( slap_syncrepl_dn_bv.bv_val, op->o_tmpmemctx );
1814         }
1815
1816         e->e_attrs = NULL;
1817
1818         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1819
1820         if( rc != LDAP_SUCCESS ) {
1821 #ifdef NEW_LOGGING
1822                 LDAP_LOG( OPERATION, ERR,
1823                         "syncrepl_updateCookie: mods2entry (%s)\n", text, 0, 0 );
1824 #else
1825                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1826                          text, 0, 0 );
1827 #endif
1828         }
1829
1830         cb.sc_response = null_callback;
1831         cb.sc_private = si;
1832
1833         op->o_callback = &cb;
1834         op->o_req_dn = e->e_name;
1835         op->o_req_ndn = e->e_nname;
1836
1837         /* update persistent cookie */
1838 update_cookie_retry:
1839         op->o_tag = LDAP_REQ_MODIFY;
1840         /* Just modify the cookie value, not the entire entry */
1841         op->orm_modlist = mod;
1842         rc = be->be_modify( op, &rs_modify );
1843
1844         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1845                 if ( rs_modify.sr_err == LDAP_REFERRAL ||
1846                          rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1847                         op->o_tag = LDAP_REQ_ADD;
1848                         op->ora_e = e;
1849                         rc = be->be_add( op, &rs_add );
1850                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1851                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS ) {
1852                                         goto update_cookie_retry;
1853                                 } else if ( rs_add.sr_err == LDAP_REFERRAL ||
1854                                                         rs_add.sr_err == LDAP_NO_SUCH_OBJECT ) {
1855 #ifdef NEW_LOGGING
1856                                         LDAP_LOG( OPERATION, ERR,
1857                                                 "cookie will be non-persistent\n",
1858                                                 0, 0, 0 );
1859 #else
1860                                         Debug( LDAP_DEBUG_ANY,
1861                                                 "cookie will be non-persistent\n",
1862                                                 0, 0, 0 );
1863 #endif
1864                                 } else {
1865 #ifdef NEW_LOGGING
1866                                         LDAP_LOG( OPERATION, ERR,
1867                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
1868 #else
1869                                         Debug( LDAP_DEBUG_ANY,
1870                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
1871 #endif
1872                                 }
1873                         } else {
1874                                 be_entry_release_w( op, e );
1875                                 goto done;
1876                         }
1877                 } else {
1878 #ifdef NEW_LOGGING
1879                         LDAP_LOG( OPERATION, ERR,
1880                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1881 #else
1882                         Debug( LDAP_DEBUG_ANY,
1883                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1884 #endif
1885                 }
1886         }
1887
1888         if ( e != NULL ) {
1889                 entry_free( e );
1890         }
1891
1892 done :
1893
1894         if ( cnbva[0].bv_val ) {
1895                 ch_free( cnbva[0].bv_val );
1896                 cnbva[0].bv_val = NULL;
1897         }
1898         if ( scbva[0].bv_val ) {
1899                 ch_free( scbva[0].bv_val );
1900                 scbva[0].bv_val = NULL;
1901         }
1902
1903         if ( mlnext->sml_next ) {
1904                 slap_mods_free( mlnext->sml_next );
1905                 mlnext->sml_next = NULL;
1906         }
1907
1908         for (ml = modlist ; ml != NULL; ml = mlnext ) {
1909                 mlnext = ml->sml_next;
1910                 free( ml );
1911         }
1912
1913         return;
1914 }
1915
1916 int
1917 syncrepl_isupdate( Operation *op )
1918 {
1919         return ( syncrepl_isupdate_dn( op->o_bd, &op->o_ndn ));
1920 }
1921
1922 int
1923 syncrepl_isupdate_dn(
1924         Backend*                be,
1925         struct berval*  ndn
1926 )
1927 {
1928         syncinfo_t*     si;
1929         int                     ret = 0;
1930
1931         if ( !LDAP_STAILQ_EMPTY( &be->be_syncinfo )) {
1932                 LDAP_STAILQ_FOREACH( si, &be->be_syncinfo, si_next ) {
1933                         if ( ( ret = dn_match( &si->si_updatedn, ndn ) ) ) {
1934                                 return ret;
1935                         }
1936                 }
1937         }
1938         return 0;
1939 }
1940
1941 static int
1942 dn_callback(
1943         Operation*      op,
1944         SlapReply*      rs
1945 )
1946 {
1947         syncinfo_t *si = op->o_callback->sc_private;
1948
1949         if ( rs->sr_type == REP_SEARCH ) {
1950                 if ( si->si_syncUUID_ndn.bv_val != NULL ) {
1951 #ifdef NEW_LOGGING
1952                         LDAP_LOG( OPERATION, ERR,
1953                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1954 #else
1955                         Debug( LDAP_DEBUG_ANY,
1956                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1957 #endif
1958                 } else {
1959                         ber_dupbv_x( &si->si_syncUUID_ndn, &rs->sr_entry->e_nname, NULL );
1960                 }
1961         } else if ( rs->sr_type == REP_RESULT ) {
1962                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
1963 #ifdef NEW_LOGGING
1964                         LDAP_LOG( OPERATION, ERR,
1965                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1966 #else
1967                         Debug( LDAP_DEBUG_ANY,
1968                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1969 #endif
1970                 }
1971         }
1972
1973         return LDAP_SUCCESS;
1974 }
1975
1976 static int
1977 nonpresent_callback(
1978         Operation*      op,
1979         SlapReply*      rs
1980 )
1981 {
1982         syncinfo_t *si = op->o_callback->sc_private;
1983         Attribute *a;
1984         int count = 0;
1985         struct berval* present_uuid = NULL;
1986         struct nonpresent_entry *np_entry;
1987
1988         if ( rs->sr_type == REP_RESULT ) {
1989                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
1990                 si->si_presentlist = NULL;
1991
1992         } else if ( rs->sr_type == REP_SEARCH ) {
1993                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
1994
1995                 if ( a == NULL ) return 0;
1996
1997                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
1998                         syncuuid_cmp );
1999
2000                 if ( present_uuid == NULL ) {
2001                         np_entry = (struct nonpresent_entry *)
2002                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2003                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2004                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2005                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2006
2007                 } else {
2008                         avl_delete( &si->si_presentlist,
2009                                         &a->a_nvals[0], syncuuid_cmp );
2010                         ch_free( present_uuid->bv_val );
2011                         ch_free( present_uuid );
2012                 }
2013         }
2014         return LDAP_SUCCESS;
2015 }
2016
2017 static int
2018 null_callback(
2019         Operation*      op,
2020         SlapReply*      rs )
2021 {
2022         if ( rs->sr_err != LDAP_SUCCESS &&
2023                 rs->sr_err != LDAP_REFERRAL &&
2024                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2025                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2026                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2027         {
2028 #ifdef NEW_LOGGING
2029                 LDAP_LOG( OPERATION, ERR,
2030                         "null_callback : error code 0x%x\n",
2031                         rs->sr_err, 0, 0 );
2032 #else
2033                 Debug( LDAP_DEBUG_ANY,
2034                         "null_callback : error code 0x%x\n",
2035                         rs->sr_err, 0, 0 );
2036 #endif
2037         }
2038         return LDAP_SUCCESS;
2039 }
2040
2041 Entry *
2042 slap_create_syncrepl_entry(
2043         Backend *be,
2044         struct berval *context_csn,
2045         struct berval *rdn,
2046         struct berval *cn )
2047 {
2048         Entry* e;
2049
2050         struct berval bv;
2051
2052         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
2053
2054         attr_merge( e, slap_schema.si_ad_objectClass, ocbva, NULL );
2055
2056         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
2057                 &ocbva[1], NULL );
2058
2059         attr_merge_one( e, slap_schema.si_ad_cn, cn, NULL );
2060
2061         if ( context_csn ) {
2062                 attr_merge_one( e, slap_schema.si_ad_syncreplCookie,
2063                         context_csn, NULL );
2064         }
2065
2066         bv.bv_val = "{}";
2067         bv.bv_len = sizeof("{}")-1;
2068         attr_merge_one( e, slap_schema.si_ad_subtreeSpecification, &bv, NULL );
2069
2070         build_new_dn( &e->e_name, &be->be_nsuffix[0], rdn, NULL );
2071         ber_dupbv( &e->e_nname, &e->e_name );
2072
2073         return e;
2074 }
2075
2076 struct berval *
2077 slap_uuidstr_from_normalized(
2078         struct berval* uuidstr,
2079         struct berval* normalized,
2080         void *ctx )
2081 {
2082         struct berval *new;
2083         unsigned char nibble;
2084         int i, d = 0;
2085
2086         if ( normalized == NULL )
2087                 return NULL;
2088
2089         if ( normalized->bv_len != 16 ) {
2090                 return NULL;
2091         }
2092
2093         if ( uuidstr ) {
2094                 new = uuidstr;
2095         } else {
2096                 new = (struct berval *)sl_malloc( sizeof(struct berval), ctx );
2097         }
2098
2099         new->bv_len = 36;
2100
2101         if (( new->bv_val = sl_malloc( new->bv_len + 1, ctx )) == NULL) {
2102                 if ( !uuidstr )
2103                         sl_free( new, ctx );
2104                 return NULL;
2105         }
2106
2107         for ( i = 0; i < 16; i++ ) {
2108                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2109                         new->bv_val[(i<<1)+d] = '-';
2110                         d += 1;
2111                 }
2112
2113                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2114                 if ( nibble < 10 ) {
2115                         new->bv_val[(i<<1)+d] = nibble + '0';
2116                 } else {
2117                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2118                 }
2119
2120                 nibble = (normalized->bv_val[i]) & 0xF;
2121                 if ( nibble < 10 ) {
2122                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2123                 } else {
2124                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2125                 }
2126         }
2127
2128         new->bv_val[new->bv_len] = '\0';
2129
2130         return new;
2131 }
2132
2133 static int
2134 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2135 {
2136         const struct berval *uuid1 = v_uuid1;
2137         const struct berval *uuid2 = v_uuid2;
2138         int rc = uuid1->bv_len - uuid2->bv_len;
2139         if ( rc ) return rc;
2140         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2141 }
2142
2143 static void
2144 avl_ber_bvfree( void *bv )
2145 {
2146         if( bv == NULL ) {
2147                 return;
2148         }
2149         if ( ((struct berval *)bv)->bv_val != NULL ) {
2150                 ch_free ( ((struct berval *)bv)->bv_val );
2151         }
2152         ch_free ( (char *) bv );
2153 }
2154
2155 void
2156 syncinfo_free( syncinfo_t *sie )
2157 {
2158         if ( sie->si_provideruri ) {
2159                 ch_free( sie->si_provideruri );
2160         }
2161         if ( sie->si_provideruri_bv ) {
2162                 ber_bvarray_free( sie->si_provideruri_bv );
2163         }
2164         if ( sie->si_updatedn.bv_val ) {
2165                 ch_free( sie->si_updatedn.bv_val );
2166         }
2167         if ( sie->si_binddn ) {
2168                 ch_free( sie->si_binddn );
2169         }
2170         if ( sie->si_passwd ) {
2171                 ch_free( sie->si_passwd );
2172         }
2173         if ( sie->si_saslmech ) {
2174                 ch_free( sie->si_saslmech );
2175         }
2176         if ( sie->si_secprops ) {
2177                 ch_free( sie->si_secprops );
2178         }
2179         if ( sie->si_realm ) {
2180                 ch_free( sie->si_realm );
2181         }
2182         if ( sie->si_authcId ) {
2183                 ch_free( sie->si_authcId );
2184         }
2185         if ( sie->si_authzId ) {
2186                 ch_free( sie->si_authzId );
2187         }
2188         if ( sie->si_filterstr.bv_val ) {
2189                 ch_free( sie->si_filterstr.bv_val );
2190         }
2191         if ( sie->si_base.bv_val ) {
2192                 ch_free( sie->si_base.bv_val );
2193         }
2194         if ( sie->si_attrs ) {
2195                 int i = 0;
2196                 while ( sie->si_attrs[i] != NULL ) {
2197                         ch_free( sie->si_attrs[i] );
2198                         i++;
2199                 }
2200                 ch_free( sie->si_attrs );
2201         }
2202         if ( sie->si_exattrs ) {
2203                 int i = 0;
2204                 while ( sie->si_exattrs[i] != NULL ) {
2205                         ch_free( sie->si_exattrs[i] );
2206                         i++;
2207                 }
2208                 ch_free( sie->si_exattrs );
2209         }
2210         if ( sie->si_retryinterval ) {
2211                 ch_free( sie->si_retryinterval );
2212         }
2213         if ( sie->si_retrynum ) {
2214                 ch_free( sie->si_retrynum );
2215         }
2216         if ( sie->si_retrynum_init ) {
2217                 ch_free( sie->si_retrynum_init );
2218         }
2219         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2220         if ( sie->si_syncUUID_ndn.bv_val ) {
2221                 ch_free( sie->si_syncUUID_ndn.bv_val );
2222         }
2223         if ( sie->si_presentlist ) {
2224             avl_free( sie->si_presentlist, avl_ber_bvfree );
2225         }
2226         if ( sie->si_ld ) {
2227                 ldap_ld_free( sie->si_ld, 1, NULL, NULL );
2228         }
2229         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2230                 struct nonpresent_entry* npe;
2231                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2232                 LDAP_LIST_REMOVE( npe, npe_link );
2233                 if ( npe->npe_name ) {
2234                         if ( npe->npe_name->bv_val ) {
2235                                 ch_free( npe->npe_name->bv_val );
2236                         }
2237                         ch_free( npe->npe_name );
2238                 }
2239                 if ( npe->npe_nname ) {
2240                         if ( npe->npe_nname->bv_val ) {
2241                                 ch_free( npe->npe_nname->bv_val );
2242                         }
2243                         ch_free( npe->npe_nname );
2244                 }
2245                 ch_free( npe );
2246         }
2247         ch_free( sie );
2248 }