s4-drs: need to set the getncchanges extended_ret on success too
[ira/wip.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         udv->version = 2;
472         udv->reserved1 = 0;
473         udv->reserved2 = 0;
474
475         werr = load_udv(sam_ctx, udv, ncRoot_dn, &ouv);
476         if (!W_ERROR_IS_OK(werr)) {
477                 return werr;
478         }
479         
480         tmp_cursor = talloc(udv, struct drsuapi_DsReplicaCursor2);
481         tmp_cursor->source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
482         tmp_cursor->highest_usn = highestUSN;
483         unix_to_nt_time(&now, t);
484         tmp_cursor->last_sync_success = now;
485
486         udv->count = ouv.ctr.ctr2.count;
487         udv->cursors = talloc_steal(udv, ouv.ctr.ctr2.cursors);
488
489         for (i=0; i<udv->count; i++) {
490                 if (GUID_equal(&tmp_cursor->source_dsa_invocation_id,
491                                &udv->cursors[i].source_dsa_invocation_id)) {
492                         udv->cursors[i] = *tmp_cursor;
493                         break;
494                 }
495         }
496         if (i == udv->count) {
497                 udv->cursors = talloc_realloc(udv, udv->cursors, struct drsuapi_DsReplicaCursor2, udv->count+1);
498                 if (!udv->cursors) {
499                         return WERR_DS_DRA_INTERNAL_ERROR;
500                 }
501                 udv->cursors[udv->count] = *tmp_cursor;
502                 udv->count++;
503         }
504         
505         qsort(udv->cursors, udv->count,
506               sizeof(struct drsuapi_DsReplicaCursor2),
507               (comparison_fn_t)drsuapi_DsReplicaCursor2_compare);
508
509         return WERR_OK;
510 }
511
512
513 /* comparison function for linked attributes - see CompareLinks() in
514  * MS-DRSR section 4.1.10.5.17 */
515 static int linked_attribute_compare(const struct drsuapi_DsReplicaLinkedAttribute *la1,
516                                     const struct drsuapi_DsReplicaLinkedAttribute *la2,
517                                     struct ldb_context *sam_ctx)
518 {
519         int c;
520         WERROR werr;
521         TALLOC_CTX *tmp_ctx;
522         const struct dsdb_schema *schema;
523         const struct dsdb_attribute *schema_attrib;
524         struct dsdb_dn *dn1, *dn2;
525         struct GUID guid1, guid2;
526         NTSTATUS status;
527
528         c = GUID_compare(&la1->identifier->guid,
529                          &la2->identifier->guid);
530         if (c != 0) return c;
531
532         if (la1->attid != la2->attid) {
533                 return la1->attid < la2->attid? -1:1;
534         }
535
536         if ((la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE) !=
537             (la2->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)) {
538                 return (la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)? 1:-1;
539         }
540
541         /* we need to get the target GUIDs to compare */
542         tmp_ctx = talloc_new(sam_ctx);
543
544         schema = dsdb_get_schema(sam_ctx);
545         schema_attrib = dsdb_attribute_by_attributeID_id(schema, la1->attid);
546
547         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la1->value.blob, &dn1);
548         if (!W_ERROR_IS_OK(werr)) {
549                 DEBUG(0,(__location__ ": Bad la1 blob in sort\n"));
550                 talloc_free(tmp_ctx);
551                 return 0;
552         }
553
554         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la2->value.blob, &dn2);
555         if (!W_ERROR_IS_OK(werr)) {
556                 DEBUG(0,(__location__ ": Bad la2 blob in sort\n"));
557                 talloc_free(tmp_ctx);
558                 return 0;
559         }
560
561         status = dsdb_get_extended_dn_guid(dn1->dn, &guid1, "GUID");
562         if (!NT_STATUS_IS_OK(status)) {
563                 DEBUG(0,(__location__ ": Bad la1 guid in sort\n"));
564                 talloc_free(tmp_ctx);
565                 return 0;
566         }
567         status = dsdb_get_extended_dn_guid(dn2->dn, &guid2, "GUID");
568         if (!NT_STATUS_IS_OK(status)) {
569                 DEBUG(0,(__location__ ": Bad la2 guid in sort\n"));
570                 talloc_free(tmp_ctx);
571                 return 0;
572         }
573
574         talloc_free(tmp_ctx);
575
576         return GUID_compare(&guid1, &guid2);
577 }
578
579
580 /*
581   sort the objects we send by tree order
582  */
583 static int site_res_cmp_parent_order(const struct ldb_message **m1, const struct ldb_message **m2)
584 {
585         return ldb_dn_compare((*m2)->dn, (*m1)->dn);
586 }
587
588 /*
589   sort the objects we send first by uSNChanged
590  */
591 static int site_res_cmp_usn_order(const struct ldb_message **m1, const struct ldb_message **m2)
592 {
593         unsigned usnchanged1, usnchanged2;
594         unsigned cn1, cn2;
595         cn1 = ldb_dn_get_comp_num((*m1)->dn);
596         cn2 = ldb_dn_get_comp_num((*m2)->dn);
597         if (cn1 != cn2) {
598                 return cn1 > cn2 ? 1 : -1;
599         }
600         usnchanged1 = ldb_msg_find_attr_as_uint(*m1, "uSNChanged", 0);
601         usnchanged2 = ldb_msg_find_attr_as_uint(*m2, "uSNChanged", 0);
602         if (usnchanged1 == usnchanged2) {
603                 return 0;
604         }
605         return usnchanged1 > usnchanged2 ? 1 : -1;
606 }
607
608
609 /*
610   handle a DRSUAPI_EXOP_FSMO_RID_ALLOC call
611  */
612 static WERROR getncchanges_rid_alloc(struct drsuapi_bind_state *b_state,
613                                      TALLOC_CTX *mem_ctx,
614                                      struct drsuapi_DsGetNCChangesRequest8 *req8,
615                                      struct drsuapi_DsGetNCChangesCtr6 *ctr6)
616 {
617         struct ldb_dn *rid_manager_dn, *fsmo_role_dn, *req_dn;
618         int ret;
619         struct ldb_context *ldb = b_state->sam_ctx;
620         struct ldb_result *ext_res;
621         struct ldb_dn *base_dn;
622         struct dsdb_fsmo_extended_op *exop;
623
624         /*
625           steps:
626             - verify that the DN being asked for is the RID Manager DN
627             - verify that we are the RID Manager
628          */
629
630         /* work out who is the RID Manager */
631         ret = samdb_rid_manager_dn(ldb, mem_ctx, &rid_manager_dn);
632         if (ret != LDB_SUCCESS) {
633                 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s\n", ldb_errstring(ldb)));
634                 return WERR_DS_DRA_INTERNAL_ERROR;
635         }
636
637         req_dn = ldb_dn_new(mem_ctx, ldb, req8->naming_context->dn);
638         if (!req_dn ||
639             !ldb_dn_validate(req_dn) ||
640             ldb_dn_compare(req_dn, rid_manager_dn) != 0) {
641                 /* that isn't the RID Manager DN */
642                 DEBUG(0,(__location__ ": RID Alloc request for wrong DN %s\n",
643                          req8->naming_context->dn));
644                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_MISMATCH;
645                 return WERR_OK;
646         }
647
648         /* find the DN of the RID Manager */
649         ret = samdb_reference_dn(ldb, mem_ctx, rid_manager_dn, "fSMORoleOwner", &fsmo_role_dn);
650         if (ret != LDB_SUCCESS) {
651                 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s\n",
652                          ldb_errstring(ldb)));
653                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
654                 return WERR_DS_DRA_INTERNAL_ERROR;
655         }
656
657         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), fsmo_role_dn) != 0) {
658                 /* we're not the RID Manager - go away */
659                 DEBUG(0,(__location__ ": RID Alloc request when not RID Manager\n"));
660                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
661                 return WERR_OK;
662         }
663
664         exop = talloc(mem_ctx, struct dsdb_fsmo_extended_op);
665         W_ERROR_HAVE_NO_MEMORY(exop);
666
667         exop->fsmo_info = req8->fsmo_info;
668         exop->destination_dsa_guid = req8->destination_dsa_guid;
669
670         ret = ldb_transaction_start(ldb);
671         if (ret != LDB_SUCCESS) {
672                 DEBUG(0,(__location__ ": Failed transaction start - %s\n",
673                          ldb_errstring(ldb)));
674                 return WERR_DS_DRA_INTERNAL_ERROR;
675         }
676
677         ret = ldb_extended(ldb, DSDB_EXTENDED_ALLOCATE_RID_POOL, exop, &ext_res);
678         if (ret != LDB_SUCCESS) {
679                 DEBUG(0,(__location__ ": Failed extended allocation RID pool operation - %s\n",
680                          ldb_errstring(ldb)));
681                 ldb_transaction_cancel(ldb);
682                 return WERR_DS_DRA_INTERNAL_ERROR;
683         }
684
685         ret = ldb_transaction_commit(ldb);
686         if (ret != LDB_SUCCESS) {
687                 DEBUG(0,(__location__ ": Failed transaction commit - %s\n",
688                          ldb_errstring(ldb)));
689                 return WERR_DS_DRA_INTERNAL_ERROR;
690         }
691
692         talloc_free(ext_res);
693
694         base_dn = samdb_base_dn(ldb);
695
696         DEBUG(2,("Allocated RID pool for server %s\n",
697                  GUID_string(mem_ctx, &req8->destination_dsa_guid)));
698
699         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
700
701         return WERR_OK;
702 }
703
704
705
706 /* state of a partially completed getncchanges call */
707 struct drsuapi_getncchanges_state {
708         struct ldb_result *site_res;
709         uint32_t num_sent;
710         struct ldb_dn *ncRoot_dn;
711         uint64_t min_usn;
712         uint64_t highest_usn;
713         struct ldb_dn *last_dn;
714         struct drsuapi_DsReplicaLinkedAttribute *la_list;
715         uint32_t la_count;
716         struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector;
717 };
718
719 /* 
720   drsuapi_DsGetNCChanges
721
722   see MS-DRSR 4.1.10.5.2 for basic logic of this function
723 */
724 WERROR dcesrv_drsuapi_DsGetNCChanges(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
725                                      struct drsuapi_DsGetNCChanges *r)
726 {
727         struct drsuapi_DsReplicaObjectIdentifier *ncRoot;
728         int ret;
729         int i;
730         struct dsdb_schema *schema;
731         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
732         struct drsuapi_DsReplicaObjectListItemEx **currentObject;
733         NTSTATUS status;
734         DATA_BLOB session_key;
735         const char *attrs[] = { "*", "distinguishedName",
736                                 "nTSecurityDescriptor",
737                                 "parentGUID",
738                                 "replPropertyMetaData",
739                                 "unicodePwd",
740                                 "dBCSPwd",
741                                 "ntPwdHistory",
742                                 "lmPwdHistory",
743                                 "supplementalCredentials",
744                                 NULL };
745         WERROR werr;
746         struct dcesrv_handle *h;
747         struct drsuapi_bind_state *b_state;     
748         struct drsuapi_getncchanges_state *getnc_state;
749         struct drsuapi_DsGetNCChangesRequest8 *req8;
750         uint32_t options;
751         uint32_t max_objects;
752         struct ldb_dn *search_dn = NULL;
753
754         DCESRV_PULL_HANDLE_WERR(h, r->in.bind_handle, DRSUAPI_BIND_HANDLE);
755         b_state = h->data;
756
757         *r->out.level_out = 6;
758         /* TODO: linked attributes*/
759         r->out.ctr->ctr6.linked_attributes_count = 0;
760         r->out.ctr->ctr6.linked_attributes = NULL;
761
762         r->out.ctr->ctr6.object_count = 0;
763         r->out.ctr->ctr6.nc_object_count = 0;
764         r->out.ctr->ctr6.more_data = false;
765         r->out.ctr->ctr6.uptodateness_vector = NULL;
766
767         /* a RODC doesn't allow for any replication */
768         if (samdb_rodc(ldb_get_opaque(b_state->sam_ctx, "loadparm"))) {
769                 DEBUG(0,(__location__ ": DsGetNCChanges attempt on RODC\n"));
770                 return WERR_DS_DRA_SOURCE_DISABLED;
771         }
772
773         /* Check request revision. 
774            TODO: Adding mappings to req8 from the other levels
775          */
776         if (r->in.level != 8) {
777                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with unsupported level %u\n",
778                          r->in.level));
779                 return WERR_REVISION_MISMATCH;
780         }
781
782         req8 = &r->in.req->req8;
783
784         /* Perform access checks. */
785         /* TODO: we need to support a sync on a specific non-root
786          * DN. We'll need to find the real partition root here */
787         ncRoot = req8->naming_context;
788         if (ncRoot == NULL) {
789                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with no NC\n"));
790                 return WERR_DS_DRA_INVALID_PARAMETER;
791         }
792
793         if (samdb_ntds_options(b_state->sam_ctx, &options) != LDB_SUCCESS) {
794                 return WERR_DS_DRA_INTERNAL_ERROR;
795         }
796         
797         if ((options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) &&
798             !(req8->replica_flags & DRSUAPI_DRS_SYNC_FORCED)) {
799                 return WERR_DS_DRA_SOURCE_DISABLED;
800         }
801
802
803         if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_SYNC_PACKET) {
804                 /* Ignore the _in_ uptpdateness vector*/
805                 req8->uptodateness_vector = NULL;
806         } 
807
808         werr = drs_security_level_check(dce_call, "DsGetNCChanges");
809         if (!W_ERROR_IS_OK(werr)) {
810                 return werr;
811         }
812
813         /* we don't yet support extended operations */
814         switch (req8->extended_op) {
815         case DRSUAPI_EXOP_NONE:
816                 break;
817
818         case DRSUAPI_EXOP_FSMO_RID_ALLOC:
819                 werr = getncchanges_rid_alloc(b_state, mem_ctx, req8, &r->out.ctr->ctr6);
820                 W_ERROR_NOT_OK_RETURN(werr);
821                 search_dn = samdb_base_dn(b_state->sam_ctx);
822                 break;
823
824         case DRSUAPI_EXOP_FSMO_REQ_ROLE:
825         case DRSUAPI_EXOP_FSMO_RID_REQ_ROLE:
826         case DRSUAPI_EXOP_FSMO_REQ_PDC:
827         case DRSUAPI_EXOP_FSMO_ABANDON_ROLE:
828         case DRSUAPI_EXOP_REPL_OBJ:
829         case DRSUAPI_EXOP_REPL_SECRET:
830                 DEBUG(0,(__location__ ": Request for DsGetNCChanges unsupported extended op 0x%x\n",
831                          (unsigned)req8->extended_op));
832                 return WERR_DS_DRA_NOT_SUPPORTED;
833         }
834
835         getnc_state = b_state->getncchanges_state;
836
837         /* see if a previous replication has been abandoned */
838         if (getnc_state) {
839                 struct ldb_dn *new_dn = ldb_dn_new(getnc_state, b_state->sam_ctx, ncRoot->dn);
840                 if (ldb_dn_compare(new_dn, getnc_state->ncRoot_dn) != 0) {
841                         DEBUG(0,(__location__ ": DsGetNCChanges 2nd replication on different DN %s %s (last_dn %s)\n",
842                                  ldb_dn_get_linearized(new_dn),
843                                  ldb_dn_get_linearized(getnc_state->ncRoot_dn),
844                                  ldb_dn_get_linearized(getnc_state->last_dn)));
845                         talloc_free(getnc_state);
846                         getnc_state = NULL;
847                 }
848         }
849
850         if (getnc_state == NULL) {
851                 getnc_state = talloc_zero(b_state, struct drsuapi_getncchanges_state);
852                 if (getnc_state == NULL) {
853                         return WERR_NOMEM;
854                 }
855                 b_state->getncchanges_state = getnc_state;
856                 getnc_state->ncRoot_dn = ldb_dn_new(getnc_state, b_state->sam_ctx, ncRoot->dn);
857         }
858
859         if (!ldb_dn_validate(getnc_state->ncRoot_dn) ||
860             ldb_dn_is_null(getnc_state->ncRoot_dn)) {
861                 DEBUG(0,(__location__ ": Bad DN '%s'\n", ncRoot->dn));
862                 return WERR_DS_DRA_INVALID_PARAMETER;
863         }
864
865         /* we need the session key for encrypting password attributes */
866         status = dcesrv_inherited_session_key(dce_call->conn, &session_key);
867         if (!NT_STATUS_IS_OK(status)) {
868                 DEBUG(0,(__location__ ": Failed to get session key\n"));
869                 return WERR_DS_DRA_INTERNAL_ERROR;              
870         }
871
872         /* 
873            TODO: MS-DRSR section 4.1.10.1.1
874            Work out if this is the start of a new cycle */
875
876         if (getnc_state->site_res == NULL) {
877                 char* search_filter;
878                 enum ldb_scope scope = LDB_SCOPE_SUBTREE;
879                 const char *extra_filter;
880
881                 extra_filter = lp_parm_string(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "object filter");
882
883                 getnc_state->min_usn = req8->highwatermark.highest_usn;
884
885                 /* Construct response. */
886                 search_filter = talloc_asprintf(mem_ctx,
887                                                 "(uSNChanged>=%llu)",
888                                                 (unsigned long long)(getnc_state->min_usn+1));
889         
890                 if (extra_filter) {
891                         search_filter = talloc_asprintf(mem_ctx, "(&%s(%s))", search_filter, extra_filter);
892                 }
893
894                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_CRITICAL_ONLY) {
895                         search_filter = talloc_asprintf(mem_ctx,
896                                                         "(&%s(isCriticalSystemObject=TRUE))",
897                                                         search_filter);
898                 }
899                 
900                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_ASYNC_REP) {
901                         scope = LDB_SCOPE_BASE;
902                 }
903                 
904                 if (!search_dn) {
905                         search_dn = getnc_state->ncRoot_dn;
906                 }
907
908                 DEBUG(1,(__location__ ": getncchanges on %s using filter %s\n",
909                          ldb_dn_get_linearized(getnc_state->ncRoot_dn), search_filter));
910                 ret = drsuapi_search_with_extended_dn(b_state->sam_ctx, getnc_state, &getnc_state->site_res,
911                                                       search_dn, scope, attrs,
912                                                       search_filter);
913                 if (ret != LDB_SUCCESS) {
914                         return WERR_DS_DRA_INTERNAL_ERROR;
915                 }
916
917                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_RETURN_OBJECT_PARENTS) {
918                         qsort(getnc_state->site_res->msgs,
919                               getnc_state->site_res->count,
920                               sizeof(getnc_state->site_res->msgs[0]),
921                               (comparison_fn_t)site_res_cmp_parent_order);
922                 } else {
923                         qsort(getnc_state->site_res->msgs,
924                               getnc_state->site_res->count,
925                               sizeof(getnc_state->site_res->msgs[0]),
926                               (comparison_fn_t)site_res_cmp_usn_order);
927                 }
928
929                 getnc_state->uptodateness_vector = talloc_steal(getnc_state, req8->uptodateness_vector);
930                 if (getnc_state->uptodateness_vector) {
931                         /* make sure its sorted */
932                         qsort(getnc_state->uptodateness_vector->cursors, 
933                               getnc_state->uptodateness_vector->count,
934                               sizeof(getnc_state->uptodateness_vector->cursors[0]),
935                               (comparison_fn_t)drsuapi_DsReplicaCursor_compare);
936                 }
937         }
938
939         /* Prefix mapping */
940         schema = dsdb_get_schema(b_state->sam_ctx);
941         if (!schema) {
942                 DEBUG(0,("No schema in sam_ctx\n"));
943                 return WERR_DS_DRA_INTERNAL_ERROR;
944         }
945
946         r->out.ctr->ctr6.naming_context = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
947         *r->out.ctr->ctr6.naming_context = *ncRoot;
948
949         if (dsdb_find_guid_by_dn(b_state->sam_ctx, getnc_state->ncRoot_dn, 
950                                  &r->out.ctr->ctr6.naming_context->guid) != LDB_SUCCESS) {
951                 DEBUG(0,(__location__ ": Failed to find GUID of ncRoot_dn %s\n",
952                          ldb_dn_get_linearized(getnc_state->ncRoot_dn)));
953                 return WERR_DS_DRA_INTERNAL_ERROR;
954         }
955
956         /* find the SID if there is one */
957         dsdb_find_sid_by_dn(b_state->sam_ctx, getnc_state->ncRoot_dn, &r->out.ctr->ctr6.naming_context->sid);
958
959         dsdb_get_oid_mappings_drsuapi(schema, true, mem_ctx, &ctr);
960         r->out.ctr->ctr6.mapping_ctr = *ctr;
961
962         r->out.ctr->ctr6.source_dsa_guid = *(samdb_ntds_objectGUID(b_state->sam_ctx));
963         r->out.ctr->ctr6.source_dsa_invocation_id = *(samdb_ntds_invocation_id(b_state->sam_ctx));
964
965         r->out.ctr->ctr6.old_highwatermark = req8->highwatermark;
966         r->out.ctr->ctr6.new_highwatermark = req8->highwatermark;
967
968         r->out.ctr->ctr6.first_object = NULL;
969         currentObject = &r->out.ctr->ctr6.first_object;
970
971         /* use this to force single objects at a time, which is useful
972          * for working out what object is giving problems
973          */
974         max_objects = lp_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max object sync", 1000);
975         if (req8->max_object_count < max_objects) {
976                 max_objects = req8->max_object_count;
977         }
978
979         for(i=getnc_state->num_sent; 
980             i<getnc_state->site_res->count && 
981                     (r->out.ctr->ctr6.object_count < max_objects);
982             i++) {
983                 int uSN;
984                 struct drsuapi_DsReplicaObjectListItemEx *obj;
985                 struct ldb_message *msg = getnc_state->site_res->msgs[i];
986
987                 obj = talloc_zero(mem_ctx, struct drsuapi_DsReplicaObjectListItemEx);
988
989                 werr = get_nc_changes_build_object(obj, msg,
990                                                    b_state->sam_ctx, getnc_state->ncRoot_dn, 
991                                                    schema, &session_key, getnc_state->min_usn,
992                                                    req8->replica_flags, getnc_state->uptodateness_vector);
993                 if (!W_ERROR_IS_OK(werr)) {
994                         return werr;
995                 }
996
997                 werr = get_nc_changes_add_links(b_state->sam_ctx, getnc_state,
998                                                 getnc_state->ncRoot_dn,
999                                                 schema, getnc_state->min_usn,
1000                                                 req8->replica_flags,
1001                                                 msg,
1002                                                 &getnc_state->la_list,
1003                                                 &getnc_state->la_count,
1004                                                 getnc_state->uptodateness_vector);
1005                 if (!W_ERROR_IS_OK(werr)) {
1006                         return werr;
1007                 }
1008
1009                 uSN = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
1010                 if (uSN > r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn) {
1011                         r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn = uSN;
1012                 }
1013                 if (uSN > getnc_state->highest_usn) {
1014                         getnc_state->highest_usn = uSN;
1015                 }
1016
1017                 if (obj->meta_data_ctr == NULL) {
1018                         DEBUG(8,(__location__ ": getncchanges skipping send of object %s\n",
1019                                  ldb_dn_get_linearized(msg->dn)));
1020                         /* no attributes to send */
1021                         talloc_free(obj);
1022                         continue;
1023                 }
1024
1025                 r->out.ctr->ctr6.object_count++;
1026                 
1027                 *currentObject = obj;
1028                 currentObject = &obj->next_object;
1029
1030                 talloc_free(getnc_state->last_dn);
1031                 getnc_state->last_dn = ldb_dn_copy(getnc_state, msg->dn);
1032
1033                 DEBUG(8,(__location__ ": replicating object %s\n", ldb_dn_get_linearized(msg->dn)));
1034         }
1035
1036         getnc_state->num_sent += r->out.ctr->ctr6.object_count;
1037
1038         r->out.ctr->ctr6.nc_object_count = getnc_state->site_res->count;
1039
1040         /* the client can us to call UpdateRefs on its behalf to
1041            re-establish monitoring of the NC */
1042         if ((req8->replica_flags & DRSUAPI_DRS_ADD_REF) && 
1043             !GUID_all_zero(&req8->destination_dsa_guid)) {
1044                 struct drsuapi_DsReplicaUpdateRefsRequest1 ureq;
1045                 ureq.naming_context = ncRoot;
1046                 ureq.dest_dsa_dns_name = talloc_asprintf(mem_ctx, "%s._msdcs.%s",
1047                                                          GUID_string(mem_ctx, &req8->destination_dsa_guid),
1048                                                          lp_realm(dce_call->conn->dce_ctx->lp_ctx));
1049                 if (!ureq.dest_dsa_dns_name) {
1050                         return WERR_NOMEM;
1051                 }
1052                 ureq.dest_dsa_guid = req8->destination_dsa_guid;
1053                 ureq.options = DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE |
1054                         DRSUAPI_DS_REPLICA_UPDATE_ASYNCHRONOUS_OPERATION |
1055                         DRSUAPI_DS_REPLICA_UPDATE_GETCHG_CHECK;
1056                 werr = drsuapi_UpdateRefs(b_state, mem_ctx, &ureq);
1057                 if (!W_ERROR_IS_OK(werr)) {
1058                         DEBUG(0,(__location__ ": Failed UpdateRefs in DsGetNCChanges - %s\n",
1059                                  win_errstr(werr)));
1060                 }
1061         }
1062
1063         if (i < getnc_state->site_res->count) {
1064                 r->out.ctr->ctr6.more_data = true;
1065         } else {
1066                 r->out.ctr->ctr6.linked_attributes_count = getnc_state->la_count;
1067                 r->out.ctr->ctr6.linked_attributes = talloc_steal(mem_ctx, getnc_state->la_list);
1068
1069                 ldb_qsort(r->out.ctr->ctr6.linked_attributes, r->out.ctr->ctr6.linked_attributes_count,
1070                           sizeof(r->out.ctr->ctr6.linked_attributes[0]),
1071                           b_state->sam_ctx, (ldb_qsort_cmp_fn_t)linked_attribute_compare);
1072
1073                 r->out.ctr->ctr6.uptodateness_vector = talloc(mem_ctx, struct drsuapi_DsReplicaCursor2CtrEx);
1074                 r->out.ctr->ctr6.new_highwatermark.highest_usn = r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn;
1075
1076                 werr = get_nc_changes_udv(b_state->sam_ctx, getnc_state->ncRoot_dn, 
1077                                           r->out.ctr->ctr6.uptodateness_vector,
1078                                           getnc_state->highest_usn);
1079                 if (!W_ERROR_IS_OK(werr)) {
1080                         return werr;
1081                 }
1082
1083                 talloc_free(getnc_state);
1084                 b_state->getncchanges_state = NULL;
1085         }
1086
1087         if (req8->extended_op != DRSUAPI_EXOP_NONE) {
1088                 r->out.ctr->ctr6.uptodateness_vector = NULL;
1089                 r->out.ctr->ctr6.nc_object_count = 0;
1090                 ZERO_STRUCT(r->out.ctr->ctr6.new_highwatermark);
1091         }
1092
1093         DEBUG(r->out.ctr->ctr6.more_data?2:1,
1094               ("DsGetNCChanges with uSNChanged >= %llu flags 0x%08x on %s gave %u objects (done %d/%d la=%d)\n",
1095                (unsigned long long)(req8->highwatermark.highest_usn+1),
1096                req8->replica_flags,
1097                ncRoot->dn, r->out.ctr->ctr6.object_count,
1098                i, r->out.ctr->ctr6.more_data?getnc_state->site_res->count:i,
1099                r->out.ctr->ctr6.linked_attributes_count));
1100
1101 #if 0
1102         if (!r->out.ctr->ctr6.more_data) {
1103                 NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsGetNCChanges, NDR_BOTH, r);
1104         }
1105 #endif
1106
1107         return WERR_OK;
1108 }