s4-drs: added filtering by udv in getncchanges
[mat/samba.git] / source4 / rpc_server / drsuapi / getncchanges.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    implement the DRSUpdateRefs call
5
6    Copyright (C) Anatoliy Atanasov 2009
7    Copyright (C) Andrew Tridgell 2009
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "rpc_server/dcerpc_server.h"
25 #include "dsdb/samdb/samdb.h"
26 #include "param/param.h"
27 #include "librpc/gen_ndr/ndr_drsblobs.h"
28 #include "librpc/gen_ndr/ndr_drsuapi.h"
29 #include "rpc_server/drsuapi/dcesrv_drsuapi.h"
30 #include "rpc_server/dcerpc_server_proto.h"
31 #include "../libcli/drsuapi/drsuapi.h"
32 #include "libcli/security/security.h"
33 #include "lib/util/binsearch.h"
34
35 /*
36   build a DsReplicaObjectIdentifier from a ldb msg
37  */
38 static struct drsuapi_DsReplicaObjectIdentifier *get_object_identifier(TALLOC_CTX *mem_ctx,
39                                                                        struct ldb_message *msg)
40 {
41         struct drsuapi_DsReplicaObjectIdentifier *identifier;
42         struct dom_sid *sid;
43
44         identifier = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
45         if (identifier == NULL) {
46                 return NULL;
47         }
48
49         identifier->dn = ldb_dn_alloc_linearized(identifier, msg->dn);
50         identifier->guid = samdb_result_guid(msg, "objectGUID");
51
52         sid = samdb_result_dom_sid(identifier, msg, "objectSid");
53         if (sid) {
54                 identifier->sid = *sid;
55         } else {
56                 ZERO_STRUCT(identifier->sid);
57         }
58         return identifier;
59 }
60
61 static int udv_compare(const struct GUID *guid1, struct GUID guid2)
62 {
63         return GUID_compare(guid1, &guid2);
64 }
65
66 /*
67   see if we can filter an attribute using the uptodateness_vector
68  */
69 static bool udv_filter(const struct drsuapi_DsReplicaCursorCtrEx *udv,
70                        const struct GUID *originating_invocation_id,
71                        uint64_t originating_usn)
72 {
73         const struct drsuapi_DsReplicaCursor *c;
74         if (udv == NULL) return false;
75         BINARY_ARRAY_SEARCH(udv->cursors, udv->count, source_dsa_invocation_id, 
76                             originating_invocation_id, udv_compare, c);
77         if (c && originating_usn <= c->highest_usn) {
78                 return true;
79         }
80         return false;
81         
82 }
83
84 /* 
85   drsuapi_DsGetNCChanges for one object
86 */
87 static WERROR get_nc_changes_build_object(struct drsuapi_DsReplicaObjectListItemEx *obj,
88                                           struct ldb_message *msg,
89                                           struct ldb_context *sam_ctx,
90                                           struct ldb_dn *ncRoot_dn,
91                                           struct dsdb_schema *schema,
92                                           DATA_BLOB *session_key,
93                                           uint64_t highest_usn,
94                                           uint32_t replica_flags,
95                                           struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector)
96 {
97         const struct ldb_val *md_value;
98         int i, n;
99         struct replPropertyMetaDataBlob md;
100         uint32_t rid = 0;
101         enum ndr_err_code ndr_err;
102         uint32_t *attids;
103         const char *rdn;
104         const struct dsdb_attribute *rdn_sa;
105
106         if (ldb_dn_compare(ncRoot_dn, msg->dn) == 0) {
107                 obj->is_nc_prefix = true;
108                 obj->parent_object_guid = NULL;
109         } else {
110                 obj->is_nc_prefix = false;
111                 obj->parent_object_guid = talloc(obj, struct GUID);
112                 if (obj->parent_object_guid == NULL) {
113                         return WERR_DS_DRA_INTERNAL_ERROR;
114                 }
115                 *obj->parent_object_guid = samdb_result_guid(msg, "parentGUID");
116                 if (GUID_all_zero(obj->parent_object_guid)) {
117                         DEBUG(0,(__location__ ": missing parentGUID for %s\n",
118                                  ldb_dn_get_linearized(msg->dn)));
119                         return WERR_DS_DRA_INTERNAL_ERROR;
120                 }
121         }
122         obj->next_object = NULL;
123         
124         md_value = ldb_msg_find_ldb_val(msg, "replPropertyMetaData");
125         if (!md_value) {
126                 /* nothing to send */
127                 return WERR_OK;
128         }
129
130         ndr_err = ndr_pull_struct_blob(md_value, obj,
131                                        lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")), &md,
132                                        (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
133         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
134                 return WERR_DS_DRA_INTERNAL_ERROR;
135         }
136         
137         if (md.version != 1) {
138                 return WERR_DS_DRA_INTERNAL_ERROR;
139         }
140
141         rdn = ldb_dn_get_rdn_name(msg->dn);
142         if (rdn == NULL) {
143                 DEBUG(0,(__location__ ": No rDN for %s\n", ldb_dn_get_linearized(msg->dn)));
144                 return WERR_DS_DRA_INTERNAL_ERROR;
145         }
146
147         rdn_sa = dsdb_attribute_by_lDAPDisplayName(schema, rdn);
148         if (rdn_sa == NULL) {
149                 DEBUG(0,(__location__ ": Can't find dsds_attribute for rDN %s in %s\n", 
150                          rdn, ldb_dn_get_linearized(msg->dn)));
151                 return WERR_DS_DRA_INTERNAL_ERROR;
152         }
153
154         obj->meta_data_ctr = talloc(obj, struct drsuapi_DsReplicaMetaDataCtr);
155         attids = talloc_array(obj, uint32_t, md.ctr.ctr1.count);
156
157         obj->object.identifier = get_object_identifier(obj, msg);
158         if (obj->object.identifier == NULL) {
159                 return WERR_NOMEM;
160         }
161         dom_sid_split_rid(NULL, &obj->object.identifier->sid, NULL, &rid);
162         
163         obj->meta_data_ctr->meta_data = talloc_array(obj, struct drsuapi_DsReplicaMetaData, md.ctr.ctr1.count);
164         for (n=i=0; i<md.ctr.ctr1.count; i++) {
165                 const struct dsdb_attribute *sa;
166                 /* if the attribute has not changed, and it is not the
167                    instanceType then don't include it */
168                 if (md.ctr.ctr1.array[i].local_usn < highest_usn &&
169                     md.ctr.ctr1.array[i].attid != DRSUAPI_ATTRIBUTE_instanceType) continue;
170
171                 /* don't include the rDN */
172                 if (md.ctr.ctr1.array[i].attid == rdn_sa->attributeID_id) continue;
173
174                 sa = dsdb_attribute_by_attributeID_id(schema, md.ctr.ctr1.array[i].attid);
175                 if (sa->linkID) {
176                         struct ldb_message_element *el;
177                         el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
178                         if (el && el->num_values && dsdb_dn_is_upgraded_link_val(&el->values[0])) {
179                                 /* don't send upgraded links inline */
180                                 continue;
181                         }
182                 }
183
184                 /* filter by uptodateness_vector */
185                 if (md.ctr.ctr1.array[i].attid != DRSUAPI_ATTRIBUTE_instanceType &&
186                     udv_filter(uptodateness_vector,
187                                &md.ctr.ctr1.array[i].originating_invocation_id, 
188                                md.ctr.ctr1.array[i].originating_usn)) {
189                         continue;
190                 }
191
192                 obj->meta_data_ctr->meta_data[n].originating_change_time = md.ctr.ctr1.array[i].originating_change_time;
193                 obj->meta_data_ctr->meta_data[n].version = md.ctr.ctr1.array[i].version;
194                 obj->meta_data_ctr->meta_data[n].originating_invocation_id = md.ctr.ctr1.array[i].originating_invocation_id;
195                 obj->meta_data_ctr->meta_data[n].originating_usn = md.ctr.ctr1.array[i].originating_usn;
196                 attids[n] = md.ctr.ctr1.array[i].attid;
197                 n++;
198         }
199
200         /* ignore it if its an empty change. Note that renames always
201          * change the 'name' attribute, so they won't be ignored by
202          * this */
203         if (n == 0 ||
204             (n == 1 && attids[0] == DRSUAPI_ATTRIBUTE_instanceType)) {
205                 talloc_free(obj->meta_data_ctr);
206                 obj->meta_data_ctr = NULL;
207                 return WERR_OK;
208         }
209
210         obj->meta_data_ctr->count = n;
211
212         obj->object.flags = DRSUAPI_DS_REPLICA_OBJECT_FROM_MASTER;
213         obj->object.attribute_ctr.num_attributes = obj->meta_data_ctr->count;
214         obj->object.attribute_ctr.attributes = talloc_array(obj, struct drsuapi_DsReplicaAttribute,
215                                                             obj->object.attribute_ctr.num_attributes);
216
217         /*
218          * Note that the meta_data array and the attributes array must
219          * be the same size and in the same order
220          */
221         for (i=0; i<obj->object.attribute_ctr.num_attributes; i++) {
222                 struct ldb_message_element *el;
223                 WERROR werr;
224                 const struct dsdb_attribute *sa;
225         
226                 sa = dsdb_attribute_by_attributeID_id(schema, attids[i]);
227                 if (!sa) {
228                         DEBUG(0,("Unable to find attributeID %u in schema\n", attids[i]));
229                         return WERR_DS_DRA_INTERNAL_ERROR;
230                 }
231
232                 el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
233                 if (el == NULL) {
234                         /* this happens for attributes that have been removed */
235                         DEBUG(5,("No element '%s' for attributeID %u in message\n",
236                                  sa->lDAPDisplayName, attids[i]));
237                         ZERO_STRUCT(obj->object.attribute_ctr.attributes[i]);
238                         obj->object.attribute_ctr.attributes[i].attid = attids[i];
239                 } else {
240                         werr = dsdb_attribute_ldb_to_drsuapi(sam_ctx, schema, el, obj,
241                                                              &obj->object.attribute_ctr.attributes[i]);
242                         if (!W_ERROR_IS_OK(werr)) {
243                                 DEBUG(0,("Unable to convert %s to DRS object - %s\n", 
244                                          sa->lDAPDisplayName, win_errstr(werr)));
245                                 return werr;
246                         }
247                         /* if DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING is set
248                          * check if attribute is secret and send a null value
249                          */
250                         if (replica_flags & DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING) {
251                                 drsuapi_process_secret_attribute(&obj->object.attribute_ctr.attributes[i],
252                                                                  &obj->meta_data_ctr->meta_data[i]);
253                         }
254                         /* some attributes needs to be encrypted
255                            before being sent */
256                         werr = drsuapi_encrypt_attribute(obj, session_key, rid, 
257                                                          &obj->object.attribute_ctr.attributes[i]);
258                         if (!W_ERROR_IS_OK(werr)) {
259                                 DEBUG(0,("Unable to encrypt %s in DRS object - %s\n", 
260                                          sa->lDAPDisplayName, win_errstr(werr)));
261                                 return werr;
262                         }
263                 }
264         }
265
266         return WERR_OK;
267 }
268
269
270 /*
271   add one linked attribute from an object to the list of linked
272   attributes in a getncchanges request
273  */
274 static WERROR get_nc_changes_add_la(TALLOC_CTX *mem_ctx,
275                                     struct ldb_context *sam_ctx,
276                                     const struct dsdb_schema *schema,
277                                     const struct dsdb_attribute *sa,
278                                     struct ldb_message *msg,
279                                     struct dsdb_dn *dsdb_dn,
280                                     struct drsuapi_DsReplicaLinkedAttribute **la_list,
281                                     uint32_t *la_count)
282 {
283         struct drsuapi_DsReplicaLinkedAttribute *la;
284         bool active;
285         NTSTATUS status;
286         WERROR werr;
287
288         (*la_list) = talloc_realloc(mem_ctx, *la_list, struct drsuapi_DsReplicaLinkedAttribute, (*la_count)+1);
289         W_ERROR_HAVE_NO_MEMORY(*la_list);
290
291         la = &(*la_list)[*la_count];
292
293         la->identifier = get_object_identifier(*la_list, msg);
294         W_ERROR_HAVE_NO_MEMORY(la->identifier);
295
296         active = (dsdb_dn_rmd_flags(dsdb_dn->dn) & DSDB_RMD_FLAG_DELETED) == 0;
297
298         la->attid = sa->attributeID_id;
299         la->flags = active?DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE:0;
300
301         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->originating_add_time, "RMD_ADDTIME");
302         if (!NT_STATUS_IS_OK(status)) {
303                 return ntstatus_to_werror(status);
304         }
305         status = dsdb_get_extended_dn_uint32(dsdb_dn->dn, &la->meta_data.version, "RMD_VERSION");
306         if (!NT_STATUS_IS_OK(status)) {
307                 return ntstatus_to_werror(status);
308         }
309         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->meta_data.originating_change_time, "RMD_CHANGETIME");
310         if (!NT_STATUS_IS_OK(status)) {
311                 return ntstatus_to_werror(status);
312         }
313         status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &la->meta_data.originating_invocation_id, "RMD_INVOCID");
314         if (!NT_STATUS_IS_OK(status)) {
315                 return ntstatus_to_werror(status);
316         }
317         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &la->meta_data.originating_usn, "RMD_ORIGINATING_USN");
318         if (!NT_STATUS_IS_OK(status)) {
319                 return ntstatus_to_werror(status);
320         }
321
322         werr = dsdb_dn_la_to_blob(sam_ctx, sa, schema, *la_list, dsdb_dn, &la->value.blob);
323         W_ERROR_NOT_OK_RETURN(werr);
324
325         (*la_count)++;
326         return WERR_OK;
327 }
328
329
330 /*
331   add linked attributes from an object to the list of linked
332   attributes in a getncchanges request
333  */
334 static WERROR get_nc_changes_add_links(struct ldb_context *sam_ctx,
335                                        TALLOC_CTX *mem_ctx,
336                                        struct ldb_dn *ncRoot_dn,
337                                        struct dsdb_schema *schema,
338                                        uint64_t highest_usn,
339                                        uint32_t replica_flags,
340                                        struct ldb_message *msg,
341                                        struct drsuapi_DsReplicaLinkedAttribute **la_list,
342                                        uint32_t *la_count,
343                                        struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector)
344 {
345         int i;
346         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
347         uint64_t uSNChanged = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
348
349         for (i=0; i<msg->num_elements; i++) {
350                 struct ldb_message_element *el = &msg->elements[i];
351                 const struct dsdb_attribute *sa;
352                 int j;
353
354                 sa = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
355
356                 if (!sa || sa->linkID == 0 || (sa->linkID & 1)) {
357                         /* we only want forward links */
358                         continue;
359                 }
360
361                 if (el->num_values && !dsdb_dn_is_upgraded_link_val(&el->values[0])) {
362                         /* its an old style link, it will have been
363                          * sent in the main replication data */
364                         continue;
365                 }
366
367                 for (j=0; j<el->num_values; j++) {
368                         struct dsdb_dn *dsdb_dn;
369                         uint64_t local_usn;
370                         NTSTATUS status;
371                         WERROR werr;
372
373                         dsdb_dn = dsdb_dn_parse(tmp_ctx, sam_ctx, &el->values[j], sa->syntax->ldap_oid);
374                         if (dsdb_dn == NULL) {
375                                 DEBUG(1,(__location__ ": Failed to parse DN for %s in %s\n",
376                                          el->name, ldb_dn_get_linearized(msg->dn)));
377                                 talloc_free(tmp_ctx);
378                                 return WERR_DS_DRA_INTERNAL_ERROR;
379                         }
380
381                         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &local_usn, "RMD_LOCAL_USN");
382                         if (!NT_STATUS_IS_OK(status)) {
383                                 /* this can happen for attributes
384                                    given to us with old style meta
385                                    data */
386                                 continue;
387                         }
388
389                         if (local_usn > uSNChanged) {
390                                 DEBUG(1,(__location__ ": uSNChanged less than RMD_LOCAL_USN for %s on %s\n",
391                                          el->name, ldb_dn_get_linearized(msg->dn)));
392                                 talloc_free(tmp_ctx);
393                                 return WERR_DS_DRA_INTERNAL_ERROR;
394                         }
395
396                         if (local_usn < highest_usn) {
397                                 continue;
398                         }
399
400                         werr = get_nc_changes_add_la(mem_ctx, sam_ctx, schema, sa, msg,
401                                                      dsdb_dn, la_list, la_count);
402                         if (!W_ERROR_IS_OK(werr)) {
403                                 talloc_free(tmp_ctx);
404                                 return werr;
405                         }
406                 }
407         }
408
409         talloc_free(tmp_ctx);
410         return WERR_OK;
411 }
412
413 /*
414   load replUpToDateVector from a DN
415  */
416 static WERROR load_udv(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
417                        struct ldb_dn *dn, struct replUpToDateVectorBlob *ouv)
418 {
419         const char *attrs[] = { "replUpToDateVector", NULL };
420         struct ldb_result *res = NULL;
421         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
422         struct ldb_message_element *el;
423         enum ndr_err_code ndr_err;
424
425         ZERO_STRUCTP(ouv);
426
427         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
428             res->count < 1) {
429                 DEBUG(0,("load_udv: failed to read partition object\n"));
430                 talloc_free(tmp_ctx);
431                 return WERR_DS_DRA_INTERNAL_ERROR;
432         }
433
434         el = ldb_msg_find_element(res->msgs[0], "replUpToDateVector");
435         if (el == NULL || el->num_values < 1) {
436                 talloc_free(tmp_ctx);
437                 ouv->version = 2;
438                 return WERR_OK;
439         }
440
441         ndr_err = ndr_pull_struct_blob(&el->values[0], 
442                                        mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
443                                        ouv, 
444                                        (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
445         talloc_free(tmp_ctx);
446         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
447                 DEBUG(0,(__location__ ": Failed to parse replUpToDateVector for %s\n",
448                          ldb_dn_get_linearized(dn)));
449                 return WERR_DS_DRA_INTERNAL_ERROR;
450         }
451         
452         return WERR_OK;
453         
454 }
455
456 /*
457   fill in the cursors return based on the replUpToDateVector for the ncRoot_dn
458  */
459 static WERROR get_nc_changes_udv(struct ldb_context *sam_ctx,
460                                  struct ldb_dn *ncRoot_dn,
461                                  struct drsuapi_DsReplicaCursor2CtrEx *udv,
462                                  uint64_t highestUSN)
463 {
464         WERROR werr;
465         struct drsuapi_DsReplicaCursor2 *tmp_cursor;
466         NTTIME now;
467         time_t t = time(NULL);
468         struct replUpToDateVectorBlob ouv;
469         int i;
470
471         werr = load_udv(sam_ctx, udv, ncRoot_dn, &ouv);
472         if (!W_ERROR_IS_OK(werr)) {
473                 return werr;
474         }
475         
476         tmp_cursor = talloc(udv, struct drsuapi_DsReplicaCursor2);
477         tmp_cursor->source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
478         tmp_cursor->highest_usn = highestUSN;
479         unix_to_nt_time(&now, t);
480         tmp_cursor->last_sync_success = now;
481
482         udv->count = ouv.ctr.ctr2.count;
483         udv->cursors = talloc_steal(udv, ouv.ctr.ctr2.cursors);
484
485         for (i=0; i<udv->count; i++) {
486                 if (GUID_equal(&tmp_cursor->source_dsa_invocation_id,
487                                &udv->cursors[i].source_dsa_invocation_id)) {
488                         udv->cursors[i] = *tmp_cursor;
489                         break;
490                 }
491         }
492         if (i == udv->count) {
493                 udv->cursors = talloc_realloc(udv, udv->cursors, struct drsuapi_DsReplicaCursor2, udv->count+1);
494                 if (!udv->cursors) {
495                         return WERR_DS_DRA_INTERNAL_ERROR;
496                 }
497                 udv->cursors[udv->count] = *tmp_cursor;
498                 udv->count++;
499         }
500         
501         qsort(udv->cursors, udv->count,
502               sizeof(struct drsuapi_DsReplicaCursor2),
503               (comparison_fn_t)drsuapi_DsReplicaCursor2_compare);
504
505         return WERR_OK;
506 }
507
508
509 /* comparison function for linked attributes - see CompareLinks() in
510  * MS-DRSR section 4.1.10.5.17 */
511 static int linked_attribute_compare(const struct drsuapi_DsReplicaLinkedAttribute *la1,
512                                     const struct drsuapi_DsReplicaLinkedAttribute *la2,
513                                     struct ldb_context *sam_ctx)
514 {
515         int c;
516         WERROR werr;
517         TALLOC_CTX *tmp_ctx;
518         const struct dsdb_schema *schema;
519         const struct dsdb_attribute *schema_attrib;
520         struct dsdb_dn *dn1, *dn2;
521         struct GUID guid1, guid2;
522         NTSTATUS status;
523
524         c = GUID_compare(&la1->identifier->guid,
525                          &la2->identifier->guid);
526         if (c != 0) return c;
527
528         if (la1->attid != la2->attid) {
529                 return la1->attid < la2->attid? -1:1;
530         }
531
532         if ((la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE) !=
533             (la2->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)) {
534                 return (la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)? 1:-1;
535         }
536
537         /* we need to get the target GUIDs to compare */
538         tmp_ctx = talloc_new(sam_ctx);
539
540         schema = dsdb_get_schema(sam_ctx);
541         schema_attrib = dsdb_attribute_by_attributeID_id(schema, la1->attid);
542
543         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la1->value.blob, &dn1);
544         if (!W_ERROR_IS_OK(werr)) {
545                 DEBUG(0,(__location__ ": Bad la1 blob in sort\n"));
546                 talloc_free(tmp_ctx);
547                 return 0;
548         }
549
550         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la2->value.blob, &dn2);
551         if (!W_ERROR_IS_OK(werr)) {
552                 DEBUG(0,(__location__ ": Bad la2 blob in sort\n"));
553                 talloc_free(tmp_ctx);
554                 return 0;
555         }
556
557         status = dsdb_get_extended_dn_guid(dn1->dn, &guid1, "GUID");
558         if (!NT_STATUS_IS_OK(status)) {
559                 DEBUG(0,(__location__ ": Bad la1 guid in sort\n"));
560                 talloc_free(tmp_ctx);
561                 return 0;
562         }
563         status = dsdb_get_extended_dn_guid(dn2->dn, &guid2, "GUID");
564         if (!NT_STATUS_IS_OK(status)) {
565                 DEBUG(0,(__location__ ": Bad la2 guid in sort\n"));
566                 talloc_free(tmp_ctx);
567                 return 0;
568         }
569
570         talloc_free(tmp_ctx);
571
572         return GUID_compare(&guid1, &guid2);
573 }
574
575
576 /*
577   sort the objects we send by tree order
578  */
579 static int site_res_cmp_parent_order(const struct ldb_message **m1, const struct ldb_message **m2)
580 {
581         return ldb_dn_compare((*m2)->dn, (*m1)->dn);
582 }
583
584 /*
585   sort the objects we send first by uSNChanged
586  */
587 static int site_res_cmp_usn_order(const struct ldb_message **m1, const struct ldb_message **m2)
588 {
589         unsigned usnchanged1, usnchanged2;
590         unsigned cn1, cn2;
591         cn1 = ldb_dn_get_comp_num((*m1)->dn);
592         cn2 = ldb_dn_get_comp_num((*m2)->dn);
593         if (cn1 != cn2) {
594                 return cn1 > cn2 ? 1 : -1;
595         }
596         usnchanged1 = ldb_msg_find_attr_as_uint(*m1, "uSNChanged", 0);
597         usnchanged2 = ldb_msg_find_attr_as_uint(*m2, "uSNChanged", 0);
598         if (usnchanged1 == usnchanged2) {
599                 return 0;
600         }
601         return usnchanged1 > usnchanged2 ? 1 : -1;
602 }
603
604
605 /*
606   handle a DRSUAPI_EXOP_FSMO_RID_ALLOC call
607  */
608 static WERROR getncchanges_rid_alloc(struct drsuapi_bind_state *b_state,
609                                      TALLOC_CTX *mem_ctx,
610                                      struct drsuapi_DsGetNCChangesRequest8 *req8,
611                                      struct drsuapi_DsGetNCChangesCtr6 *ctr6)
612 {
613         struct ldb_dn *rid_manager_dn, *fsmo_role_dn, *req_dn;
614         int ret;
615         struct ldb_context *ldb = b_state->sam_ctx;
616         struct ldb_result *ext_res;
617         struct ldb_dn *base_dn;
618         struct dsdb_fsmo_extended_op *exop;
619
620         /*
621           steps:
622             - verify that the DN being asked for is the RID Manager DN
623             - verify that we are the RID Manager
624          */
625
626         /* work out who is the RID Manager */
627         ret = samdb_rid_manager_dn(ldb, mem_ctx, &rid_manager_dn);
628         if (ret != LDB_SUCCESS) {
629                 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s\n", ldb_errstring(ldb)));
630                 return WERR_DS_DRA_INTERNAL_ERROR;
631         }
632
633         req_dn = ldb_dn_new(mem_ctx, ldb, req8->naming_context->dn);
634         if (!req_dn ||
635             !ldb_dn_validate(req_dn) ||
636             ldb_dn_compare(req_dn, rid_manager_dn) != 0) {
637                 /* that isn't the RID Manager DN */
638                 DEBUG(0,(__location__ ": RID Alloc request for wrong DN %s\n",
639                          req8->naming_context->dn));
640                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_MISMATCH;
641                 return WERR_OK;
642         }
643
644         /* find the DN of the RID Manager */
645         ret = samdb_reference_dn(ldb, mem_ctx, rid_manager_dn, "fSMORoleOwner", &fsmo_role_dn);
646         if (ret != LDB_SUCCESS) {
647                 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s\n",
648                          ldb_errstring(ldb)));
649                 return WERR_DS_DRA_INTERNAL_ERROR;
650         }
651
652         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), fsmo_role_dn) != 0) {
653                 /* we're not the RID Manager - go away */
654                 DEBUG(0,(__location__ ": RID Alloc request when not RID Manager\n"));
655                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
656                 return WERR_OK;
657         }
658
659         exop = talloc(mem_ctx, struct dsdb_fsmo_extended_op);
660         W_ERROR_HAVE_NO_MEMORY(exop);
661
662         exop->fsmo_info = req8->fsmo_info;
663         exop->destination_dsa_guid = req8->destination_dsa_guid;
664
665         ret = ldb_transaction_start(ldb);
666         if (ret != LDB_SUCCESS) {
667                 DEBUG(0,(__location__ ": Failed transaction start - %s\n",
668                          ldb_errstring(ldb)));
669                 return WERR_DS_DRA_INTERNAL_ERROR;
670         }
671
672         ret = ldb_extended(ldb, DSDB_EXTENDED_ALLOCATE_RID_POOL, exop, &ext_res);
673         if (ret != LDB_SUCCESS) {
674                 DEBUG(0,(__location__ ": Failed extended allocation RID pool operation - %s\n",
675                          ldb_errstring(ldb)));
676                 ldb_transaction_cancel(ldb);
677                 return WERR_DS_DRA_INTERNAL_ERROR;
678         }
679
680         ret = ldb_transaction_commit(ldb);
681         if (ret != LDB_SUCCESS) {
682                 DEBUG(0,(__location__ ": Failed transaction commit - %s\n",
683                          ldb_errstring(ldb)));
684                 return WERR_DS_DRA_INTERNAL_ERROR;
685         }
686
687         talloc_free(ext_res);
688
689         base_dn = samdb_base_dn(ldb);
690
691         DEBUG(2,("Allocated RID pool for server %s\n",
692                  GUID_string(mem_ctx, &req8->destination_dsa_guid)));
693
694         return WERR_OK;
695 }
696
697
698
699 /* state of a partially completed getncchanges call */
700 struct drsuapi_getncchanges_state {
701         struct ldb_result *site_res;
702         uint32_t num_sent;
703         struct ldb_dn *ncRoot_dn;
704         uint64_t min_usn;
705         uint64_t highest_usn;
706         struct ldb_dn *last_dn;
707         struct drsuapi_DsReplicaLinkedAttribute *la_list;
708         uint32_t la_count;
709         struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector;
710 };
711
712 /* 
713   drsuapi_DsGetNCChanges
714
715   see MS-DRSR 4.1.10.5.2 for basic logic of this function
716 */
717 WERROR dcesrv_drsuapi_DsGetNCChanges(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
718                                      struct drsuapi_DsGetNCChanges *r)
719 {
720         struct drsuapi_DsReplicaObjectIdentifier *ncRoot;
721         int ret;
722         int i;
723         struct dsdb_schema *schema;
724         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
725         struct drsuapi_DsReplicaObjectListItemEx **currentObject;
726         NTSTATUS status;
727         DATA_BLOB session_key;
728         const char *attrs[] = { "*", "distinguishedName",
729                                 "nTSecurityDescriptor",
730                                 "parentGUID",
731                                 "replPropertyMetaData",
732                                 "unicodePwd",
733                                 "dBCSPwd",
734                                 "ntPwdHistory",
735                                 "lmPwdHistory",
736                                 "supplementalCredentials",
737                                 NULL };
738         WERROR werr;
739         struct dcesrv_handle *h;
740         struct drsuapi_bind_state *b_state;     
741         struct drsuapi_getncchanges_state *getnc_state;
742         struct drsuapi_DsGetNCChangesRequest8 *req8;
743         uint32_t options;
744         uint32_t max_objects;
745         struct ldb_dn *search_dn = NULL;
746
747         DCESRV_PULL_HANDLE_WERR(h, r->in.bind_handle, DRSUAPI_BIND_HANDLE);
748         b_state = h->data;
749
750         *r->out.level_out = 6;
751         /* TODO: linked attributes*/
752         r->out.ctr->ctr6.linked_attributes_count = 0;
753         r->out.ctr->ctr6.linked_attributes = NULL;
754
755         r->out.ctr->ctr6.object_count = 0;
756         r->out.ctr->ctr6.nc_object_count = 0;
757         r->out.ctr->ctr6.more_data = false;
758         r->out.ctr->ctr6.uptodateness_vector = NULL;
759
760         /* a RODC doesn't allow for any replication */
761         if (samdb_rodc(ldb_get_opaque(b_state->sam_ctx, "loadparm"))) {
762                 DEBUG(0,(__location__ ": DsGetNCChanges attempt on RODC\n"));
763                 return WERR_DS_DRA_SOURCE_DISABLED;
764         }
765
766         /* Check request revision. 
767            TODO: Adding mappings to req8 from the other levels
768          */
769         if (r->in.level != 8) {
770                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with unsupported level %u\n",
771                          r->in.level));
772                 return WERR_REVISION_MISMATCH;
773         }
774
775         req8 = &r->in.req->req8;
776
777         /* Perform access checks. */
778         /* TODO: we need to support a sync on a specific non-root
779          * DN. We'll need to find the real partition root here */
780         ncRoot = req8->naming_context;
781         if (ncRoot == NULL) {
782                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with no NC\n"));
783                 return WERR_DS_DRA_INVALID_PARAMETER;
784         }
785
786         if (samdb_ntds_options(b_state->sam_ctx, &options) != LDB_SUCCESS) {
787                 return WERR_DS_DRA_INTERNAL_ERROR;
788         }
789         
790         if ((options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) &&
791             !(req8->replica_flags & DRSUAPI_DRS_SYNC_FORCED)) {
792                 return WERR_DS_DRA_SOURCE_DISABLED;
793         }
794
795
796         if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_SYNC_PACKET) {
797                 /* Ignore the _in_ uptpdateness vector*/
798                 req8->uptodateness_vector = NULL;
799         } 
800
801         werr = drs_security_level_check(dce_call, "DsGetNCChanges");
802         if (!W_ERROR_IS_OK(werr)) {
803                 return werr;
804         }
805
806         /* we don't yet support extended operations */
807         switch (req8->extended_op) {
808         case DRSUAPI_EXOP_NONE:
809                 break;
810
811         case DRSUAPI_EXOP_FSMO_RID_ALLOC:
812                 werr = getncchanges_rid_alloc(b_state, mem_ctx, req8, &r->out.ctr->ctr6);
813                 W_ERROR_NOT_OK_RETURN(werr);
814                 search_dn = samdb_base_dn(b_state->sam_ctx);
815                 break;
816
817         case DRSUAPI_EXOP_FSMO_REQ_ROLE:
818         case DRSUAPI_EXOP_FSMO_RID_REQ_ROLE:
819         case DRSUAPI_EXOP_FSMO_REQ_PDC:
820         case DRSUAPI_EXOP_FSMO_ABANDON_ROLE:
821         case DRSUAPI_EXOP_REPL_OBJ:
822         case DRSUAPI_EXOP_REPL_SECRET:
823                 DEBUG(0,(__location__ ": Request for DsGetNCChanges unsupported extended op 0x%x\n",
824                          (unsigned)req8->extended_op));
825                 return WERR_DS_DRA_NOT_SUPPORTED;
826         }
827
828         getnc_state = b_state->getncchanges_state;
829
830         /* see if a previous replication has been abandoned */
831         if (getnc_state) {
832                 struct ldb_dn *new_dn = ldb_dn_new(getnc_state, b_state->sam_ctx, ncRoot->dn);
833                 if (ldb_dn_compare(new_dn, getnc_state->ncRoot_dn) != 0) {
834                         DEBUG(0,(__location__ ": DsGetNCChanges 2nd replication on different DN %s %s (last_dn %s)\n",
835                                  ldb_dn_get_linearized(new_dn),
836                                  ldb_dn_get_linearized(getnc_state->ncRoot_dn),
837                                  ldb_dn_get_linearized(getnc_state->last_dn)));
838                         talloc_free(getnc_state);
839                         getnc_state = NULL;
840                 }
841         }
842
843         if (getnc_state == NULL) {
844                 getnc_state = talloc_zero(b_state, struct drsuapi_getncchanges_state);
845                 if (getnc_state == NULL) {
846                         return WERR_NOMEM;
847                 }
848                 b_state->getncchanges_state = getnc_state;
849                 getnc_state->ncRoot_dn = ldb_dn_new(getnc_state, b_state->sam_ctx, ncRoot->dn);
850         }
851
852         if (!ldb_dn_validate(getnc_state->ncRoot_dn) ||
853             ldb_dn_is_null(getnc_state->ncRoot_dn)) {
854                 DEBUG(0,(__location__ ": Bad DN '%s'\n", ncRoot->dn));
855                 return WERR_DS_DRA_INVALID_PARAMETER;
856         }
857
858         /* we need the session key for encrypting password attributes */
859         status = dcesrv_inherited_session_key(dce_call->conn, &session_key);
860         if (!NT_STATUS_IS_OK(status)) {
861                 DEBUG(0,(__location__ ": Failed to get session key\n"));
862                 return WERR_DS_DRA_INTERNAL_ERROR;              
863         }
864
865         /* 
866            TODO: MS-DRSR section 4.1.10.1.1
867            Work out if this is the start of a new cycle */
868
869         if (getnc_state->site_res == NULL) {
870                 char* search_filter;
871                 enum ldb_scope scope = LDB_SCOPE_SUBTREE;
872                 const char *extra_filter;
873
874                 extra_filter = lp_parm_string(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "object filter");
875
876                 getnc_state->min_usn = req8->highwatermark.highest_usn;
877
878                 /* Construct response. */
879                 search_filter = talloc_asprintf(mem_ctx,
880                                                 "(uSNChanged>=%llu)",
881                                                 (unsigned long long)(getnc_state->min_usn+1));
882         
883                 if (extra_filter) {
884                         search_filter = talloc_asprintf(mem_ctx, "(&%s(%s))", search_filter, extra_filter);
885                 }
886
887                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_CRITICAL_ONLY) {
888                         search_filter = talloc_asprintf(mem_ctx,
889                                                         "(&%s(isCriticalSystemObject=TRUE))",
890                                                         search_filter);
891                 }
892                 
893                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_ASYNC_REP) {
894                         scope = LDB_SCOPE_BASE;
895                 }
896                 
897                 if (!search_dn) {
898                         search_dn = getnc_state->ncRoot_dn;
899                 }
900
901                 DEBUG(1,(__location__ ": getncchanges on %s using filter %s\n",
902                          ldb_dn_get_linearized(getnc_state->ncRoot_dn), search_filter));
903                 ret = drsuapi_search_with_extended_dn(b_state->sam_ctx, getnc_state, &getnc_state->site_res,
904                                                       search_dn, scope, attrs,
905                                                       search_filter);
906                 if (ret != LDB_SUCCESS) {
907                         return WERR_DS_DRA_INTERNAL_ERROR;
908                 }
909
910                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_RETURN_OBJECT_PARENTS) {
911                         qsort(getnc_state->site_res->msgs,
912                               getnc_state->site_res->count,
913                               sizeof(getnc_state->site_res->msgs[0]),
914                               (comparison_fn_t)site_res_cmp_parent_order);
915                 } else {
916                         qsort(getnc_state->site_res->msgs,
917                               getnc_state->site_res->count,
918                               sizeof(getnc_state->site_res->msgs[0]),
919                               (comparison_fn_t)site_res_cmp_usn_order);
920                 }
921
922                 getnc_state->uptodateness_vector = talloc_steal(getnc_state, req8->uptodateness_vector);
923                 if (getnc_state->uptodateness_vector) {
924                         /* make sure its sorted */
925                         qsort(getnc_state->uptodateness_vector->cursors, 
926                               getnc_state->uptodateness_vector->count,
927                               sizeof(getnc_state->uptodateness_vector->cursors[0]),
928                               (comparison_fn_t)drsuapi_DsReplicaCursor_compare);
929                 }
930         }
931
932         /* Prefix mapping */
933         schema = dsdb_get_schema(b_state->sam_ctx);
934         if (!schema) {
935                 DEBUG(0,("No schema in sam_ctx\n"));
936                 return WERR_DS_DRA_INTERNAL_ERROR;
937         }
938
939         r->out.ctr->ctr6.naming_context = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
940         *r->out.ctr->ctr6.naming_context = *ncRoot;
941
942         if (dsdb_find_guid_by_dn(b_state->sam_ctx, getnc_state->ncRoot_dn, 
943                                  &r->out.ctr->ctr6.naming_context->guid) != LDB_SUCCESS) {
944                 DEBUG(0,(__location__ ": Failed to find GUID of ncRoot_dn %s\n",
945                          ldb_dn_get_linearized(getnc_state->ncRoot_dn)));
946                 return WERR_DS_DRA_INTERNAL_ERROR;
947         }
948
949         /* find the SID if there is one */
950         dsdb_find_sid_by_dn(b_state->sam_ctx, getnc_state->ncRoot_dn, &r->out.ctr->ctr6.naming_context->sid);
951
952         dsdb_get_oid_mappings_drsuapi(schema, true, mem_ctx, &ctr);
953         r->out.ctr->ctr6.mapping_ctr = *ctr;
954
955         r->out.ctr->ctr6.source_dsa_guid = *(samdb_ntds_objectGUID(b_state->sam_ctx));
956         r->out.ctr->ctr6.source_dsa_invocation_id = *(samdb_ntds_invocation_id(b_state->sam_ctx));
957
958         r->out.ctr->ctr6.old_highwatermark = req8->highwatermark;
959         r->out.ctr->ctr6.new_highwatermark = req8->highwatermark;
960
961         r->out.ctr->ctr6.first_object = NULL;
962         currentObject = &r->out.ctr->ctr6.first_object;
963
964         /* use this to force single objects at a time, which is useful
965          * for working out what object is giving problems
966          */
967         max_objects = lp_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max object sync", 1000);
968         if (req8->max_object_count < max_objects) {
969                 max_objects = req8->max_object_count;
970         }
971
972         for(i=getnc_state->num_sent; 
973             i<getnc_state->site_res->count && 
974                     (r->out.ctr->ctr6.object_count < max_objects);
975             i++) {
976                 int uSN;
977                 struct drsuapi_DsReplicaObjectListItemEx *obj;
978                 struct ldb_message *msg = getnc_state->site_res->msgs[i];
979
980                 obj = talloc_zero(mem_ctx, struct drsuapi_DsReplicaObjectListItemEx);
981
982                 werr = get_nc_changes_build_object(obj, msg,
983                                                    b_state->sam_ctx, getnc_state->ncRoot_dn, 
984                                                    schema, &session_key, getnc_state->min_usn,
985                                                    req8->replica_flags, getnc_state->uptodateness_vector);
986                 if (!W_ERROR_IS_OK(werr)) {
987                         return werr;
988                 }
989
990                 werr = get_nc_changes_add_links(b_state->sam_ctx, getnc_state,
991                                                 getnc_state->ncRoot_dn,
992                                                 schema, getnc_state->min_usn,
993                                                 req8->replica_flags,
994                                                 msg,
995                                                 &getnc_state->la_list,
996                                                 &getnc_state->la_count,
997                                                 getnc_state->uptodateness_vector);
998                 if (!W_ERROR_IS_OK(werr)) {
999                         return werr;
1000                 }
1001
1002                 uSN = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
1003                 if (uSN > r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn) {
1004                         r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn = uSN;
1005                 }
1006                 if (uSN > getnc_state->highest_usn) {
1007                         getnc_state->highest_usn = uSN;
1008                 }
1009
1010                 if (obj->meta_data_ctr == NULL) {
1011                         DEBUG(0,(__location__ ": getncchanges skipping send of object %s\n",
1012                                  ldb_dn_get_linearized(msg->dn)));
1013                         /* no attributes to send */
1014                         talloc_free(obj);
1015                         continue;
1016                 }
1017
1018                 r->out.ctr->ctr6.object_count++;
1019                 
1020                 *currentObject = obj;
1021                 currentObject = &obj->next_object;
1022
1023                 talloc_free(getnc_state->last_dn);
1024                 getnc_state->last_dn = ldb_dn_copy(getnc_state, msg->dn);
1025
1026                 DEBUG(8,(__location__ ": replicating object %s\n", ldb_dn_get_linearized(msg->dn)));
1027         }
1028
1029         getnc_state->num_sent += r->out.ctr->ctr6.object_count;
1030
1031         r->out.ctr->ctr6.nc_object_count = getnc_state->site_res->count;
1032
1033         /* the client can us to call UpdateRefs on its behalf to
1034            re-establish monitoring of the NC */
1035         if ((req8->replica_flags & DRSUAPI_DRS_ADD_REF) && 
1036             !GUID_all_zero(&req8->destination_dsa_guid)) {
1037                 struct drsuapi_DsReplicaUpdateRefsRequest1 ureq;
1038                 ureq.naming_context = ncRoot;
1039                 ureq.dest_dsa_dns_name = talloc_asprintf(mem_ctx, "%s._msdcs.%s",
1040                                                          GUID_string(mem_ctx, &req8->destination_dsa_guid),
1041                                                          lp_realm(dce_call->conn->dce_ctx->lp_ctx));
1042                 if (!ureq.dest_dsa_dns_name) {
1043                         return WERR_NOMEM;
1044                 }
1045                 ureq.dest_dsa_guid = req8->destination_dsa_guid;
1046                 ureq.options = DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE |
1047                         DRSUAPI_DS_REPLICA_UPDATE_ASYNCHRONOUS_OPERATION |
1048                         DRSUAPI_DS_REPLICA_UPDATE_GETCHG_CHECK;
1049                 werr = drsuapi_UpdateRefs(b_state, mem_ctx, &ureq);
1050                 if (!W_ERROR_IS_OK(werr)) {
1051                         DEBUG(0,(__location__ ": Failed UpdateRefs in DsGetNCChanges - %s\n",
1052                                  win_errstr(werr)));
1053                 }
1054         }
1055
1056         if (i < getnc_state->site_res->count) {
1057                 r->out.ctr->ctr6.more_data = true;
1058         } else {
1059                 r->out.ctr->ctr6.linked_attributes_count = getnc_state->la_count;
1060                 r->out.ctr->ctr6.linked_attributes = talloc_steal(mem_ctx, getnc_state->la_list);
1061
1062                 ldb_qsort(r->out.ctr->ctr6.linked_attributes, r->out.ctr->ctr6.linked_attributes_count,
1063                           sizeof(r->out.ctr->ctr6.linked_attributes[0]),
1064                           b_state->sam_ctx, (ldb_qsort_cmp_fn_t)linked_attribute_compare);
1065
1066                 r->out.ctr->ctr6.uptodateness_vector = talloc(mem_ctx, struct drsuapi_DsReplicaCursor2CtrEx);
1067                 r->out.ctr->ctr6.uptodateness_vector->version = 2;
1068                 r->out.ctr->ctr6.uptodateness_vector->reserved1 = 0;
1069                 r->out.ctr->ctr6.uptodateness_vector->reserved2 = 0;
1070
1071                 r->out.ctr->ctr6.new_highwatermark.highest_usn = r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn;
1072
1073                 werr = get_nc_changes_udv(b_state->sam_ctx, getnc_state->ncRoot_dn, 
1074                                           r->out.ctr->ctr6.uptodateness_vector,
1075                                           getnc_state->highest_usn);
1076                 if (!W_ERROR_IS_OK(werr)) {
1077                         return werr;
1078                 }
1079
1080                 talloc_free(getnc_state);
1081                 b_state->getncchanges_state = NULL;
1082         }
1083
1084         if (req8->extended_op != DRSUAPI_EXOP_NONE) {
1085                 r->out.ctr->ctr6.uptodateness_vector = NULL;
1086                 r->out.ctr->ctr6.nc_object_count = 0;
1087                 ZERO_STRUCT(r->out.ctr->ctr6.new_highwatermark);
1088         }
1089
1090         DEBUG(r->out.ctr->ctr6.more_data?2:1,
1091               ("DsGetNCChanges with uSNChanged >= %llu flags 0x%08x on %s gave %u objects (done %d/%d la=%d)\n",
1092                (unsigned long long)(req8->highwatermark.highest_usn+1),
1093                req8->replica_flags,
1094                ncRoot->dn, r->out.ctr->ctr6.object_count,
1095                i, r->out.ctr->ctr6.more_data?getnc_state->site_res->count:i,
1096                r->out.ctr->ctr6.linked_attributes_count));
1097
1098 #if 0
1099         if (!r->out.ctr->ctr6.more_data) {
1100                 NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsGetNCChanges, NDR_BOTH, r);
1101         }
1102 #endif
1103
1104         return WERR_OK;
1105 }