s4-drs: implement PAS checks and access checks for getncchanges
[nivanova/samba-autobuild/.git] / source4 / rpc_server / drsuapi / getncchanges.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    implement the DSGetNCChanges 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 "librpc/gen_ndr/ndr_security.h"
30 #include "rpc_server/drsuapi/dcesrv_drsuapi.h"
31 #include "rpc_server/dcerpc_server_proto.h"
32 #include "../libcli/drsuapi/drsuapi.h"
33 #include "libcli/security/security.h"
34 #include "lib/util/binsearch.h"
35 #include "lib/util/tsort.h"
36 #include "auth/session.h"
37 #include "dsdb/common/util.h"
38
39 /*
40   build a DsReplicaObjectIdentifier from a ldb msg
41  */
42 static struct drsuapi_DsReplicaObjectIdentifier *get_object_identifier(TALLOC_CTX *mem_ctx,
43                                                                        struct ldb_message *msg)
44 {
45         struct drsuapi_DsReplicaObjectIdentifier *identifier;
46         struct dom_sid *sid;
47
48         identifier = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
49         if (identifier == NULL) {
50                 return NULL;
51         }
52
53         identifier->dn = ldb_dn_alloc_linearized(identifier, msg->dn);
54         identifier->guid = samdb_result_guid(msg, "objectGUID");
55
56         sid = samdb_result_dom_sid(identifier, msg, "objectSid");
57         if (sid) {
58                 identifier->sid = *sid;
59         } else {
60                 ZERO_STRUCT(identifier->sid);
61         }
62         return identifier;
63 }
64
65 static int udv_compare(const struct GUID *guid1, struct GUID guid2)
66 {
67         return GUID_compare(guid1, &guid2);
68 }
69
70 /*
71   see if we can filter an attribute using the uptodateness_vector
72  */
73 static bool udv_filter(const struct drsuapi_DsReplicaCursorCtrEx *udv,
74                        const struct GUID *originating_invocation_id,
75                        uint64_t originating_usn)
76 {
77         const struct drsuapi_DsReplicaCursor *c;
78         if (udv == NULL) return false;
79         BINARY_ARRAY_SEARCH(udv->cursors, udv->count, source_dsa_invocation_id, 
80                             originating_invocation_id, udv_compare, c);
81         if (c && originating_usn <= c->highest_usn) {
82                 return true;
83         }
84         return false;
85         
86 }
87
88 static int attid_cmp(enum drsuapi_DsAttributeId a1, enum drsuapi_DsAttributeId a2)
89 {
90         if (a1 == a2) return 0;
91         return ((uint32_t)a1) > ((uint32_t)a2) ? 1 : -1;
92 }
93
94 /*
95   check if an attribute is in a partial_attribute_set
96  */
97 static bool check_partial_attribute_set(const struct dsdb_attribute *sa,
98                                         struct drsuapi_DsPartialAttributeSet *pas)
99 {
100         enum drsuapi_DsAttributeId *result;
101         BINARY_ARRAY_SEARCH_V(pas->attids, pas->num_attids, (enum drsuapi_DsAttributeId)sa->attributeID_id,
102                               attid_cmp, result);
103         return result != NULL;
104 }
105
106
107 /* 
108   drsuapi_DsGetNCChanges for one object
109 */
110 static WERROR get_nc_changes_build_object(struct drsuapi_DsReplicaObjectListItemEx *obj,
111                                           struct ldb_message *msg,
112                                           struct ldb_context *sam_ctx,
113                                           struct ldb_dn *ncRoot_dn,
114                                           bool   is_schema_nc,
115                                           struct dsdb_schema *schema,
116                                           DATA_BLOB *session_key,
117                                           uint64_t highest_usn,
118                                           uint32_t replica_flags,
119                                           struct drsuapi_DsPartialAttributeSet *partial_attribute_set,
120                                           struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector,
121                                           enum drsuapi_DsExtendedOperation extended_op)
122 {
123         const struct ldb_val *md_value;
124         unsigned int i, n;
125         struct replPropertyMetaDataBlob md;
126         uint32_t rid = 0;
127         enum ndr_err_code ndr_err;
128         uint32_t *attids;
129         const char *rdn;
130         const struct dsdb_attribute *rdn_sa;
131         unsigned int instanceType;
132         struct dsdb_syntax_ctx syntax_ctx;
133
134         /* make dsdb sytanx context for conversions */
135         dsdb_syntax_ctx_init(&syntax_ctx, sam_ctx, schema);
136         syntax_ctx.is_schema_nc = is_schema_nc;
137
138         instanceType = ldb_msg_find_attr_as_uint(msg, "instanceType", 0);
139         if (instanceType & INSTANCE_TYPE_IS_NC_HEAD) {
140                 obj->is_nc_prefix = true;
141                 obj->parent_object_guid = NULL;
142         } else {
143                 obj->is_nc_prefix = false;
144                 obj->parent_object_guid = talloc(obj, struct GUID);
145                 if (obj->parent_object_guid == NULL) {
146                         return WERR_DS_DRA_INTERNAL_ERROR;
147                 }
148                 *obj->parent_object_guid = samdb_result_guid(msg, "parentGUID");
149                 if (GUID_all_zero(obj->parent_object_guid)) {
150                         DEBUG(0,(__location__ ": missing parentGUID for %s\n",
151                                  ldb_dn_get_linearized(msg->dn)));
152                         return WERR_DS_DRA_INTERNAL_ERROR;
153                 }
154         }
155         obj->next_object = NULL;
156         
157         md_value = ldb_msg_find_ldb_val(msg, "replPropertyMetaData");
158         if (!md_value) {
159                 /* nothing to send */
160                 return WERR_OK;
161         }
162
163         if (instanceType & INSTANCE_TYPE_UNINSTANT) {
164                 /* don't send uninstantiated objects */
165                 return WERR_OK;
166         }
167
168         ndr_err = ndr_pull_struct_blob(md_value, obj, &md,
169                                        (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
170         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
171                 return WERR_DS_DRA_INTERNAL_ERROR;
172         }
173         
174         if (md.version != 1) {
175                 return WERR_DS_DRA_INTERNAL_ERROR;
176         }
177
178         rdn = ldb_dn_get_rdn_name(msg->dn);
179         if (rdn == NULL) {
180                 DEBUG(0,(__location__ ": No rDN for %s\n", ldb_dn_get_linearized(msg->dn)));
181                 return WERR_DS_DRA_INTERNAL_ERROR;
182         }
183
184         rdn_sa = dsdb_attribute_by_lDAPDisplayName(schema, rdn);
185         if (rdn_sa == NULL) {
186                 DEBUG(0,(__location__ ": Can't find dsds_attribute for rDN %s in %s\n", 
187                          rdn, ldb_dn_get_linearized(msg->dn)));
188                 return WERR_DS_DRA_INTERNAL_ERROR;
189         }
190
191         obj->meta_data_ctr = talloc(obj, struct drsuapi_DsReplicaMetaDataCtr);
192         attids = talloc_array(obj, uint32_t, md.ctr.ctr1.count);
193
194         obj->object.identifier = get_object_identifier(obj, msg);
195         if (obj->object.identifier == NULL) {
196                 return WERR_NOMEM;
197         }
198         dom_sid_split_rid(NULL, &obj->object.identifier->sid, NULL, &rid);
199         
200         obj->meta_data_ctr->meta_data = talloc_array(obj, struct drsuapi_DsReplicaMetaData, md.ctr.ctr1.count);
201         for (n=i=0; i<md.ctr.ctr1.count; i++) {
202                 const struct dsdb_attribute *sa;
203                 bool force_attribute = false;
204
205                 /* if the attribute has not changed, and it is not the
206                    instanceType then don't include it */
207                 if (md.ctr.ctr1.array[i].local_usn < highest_usn &&
208                     extended_op != DRSUAPI_EXOP_REPL_SECRET &&
209                     md.ctr.ctr1.array[i].attid != DRSUAPI_ATTRIBUTE_instanceType) continue;
210
211                 /* don't include the rDN */
212                 if (md.ctr.ctr1.array[i].attid == rdn_sa->attributeID_id) continue;
213
214                 sa = dsdb_attribute_by_attributeID_id(schema, md.ctr.ctr1.array[i].attid);
215                 if (!sa) {
216                         DEBUG(0,(__location__ ": Failed to find attribute in schema for attrid %u mentioned in replPropertyMetaData of %s\n", 
217                                  (unsigned int)md.ctr.ctr1.array[i].attid, 
218                                  ldb_dn_get_linearized(msg->dn)));
219                         return WERR_DS_DRA_INTERNAL_ERROR;              
220                 }
221
222                 if (sa->linkID) {
223                         struct ldb_message_element *el;
224                         el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
225                         if (el && el->num_values && dsdb_dn_is_upgraded_link_val(&el->values[0])) {
226                                 /* don't send upgraded links inline */
227                                 continue;
228                         }
229                 }
230
231                 if (extended_op == DRSUAPI_EXOP_REPL_SECRET &&
232                     !dsdb_attr_in_rodc_fas(sa)) {
233                         force_attribute = true;
234                         DEBUG(4,("Forcing attribute %s in %s\n",
235                                  sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
236                 }
237
238                 /* filter by uptodateness_vector */
239                 if (md.ctr.ctr1.array[i].attid != DRSUAPI_ATTRIBUTE_instanceType &&
240                     !force_attribute &&
241                     udv_filter(uptodateness_vector,
242                                &md.ctr.ctr1.array[i].originating_invocation_id, 
243                                md.ctr.ctr1.array[i].originating_usn)) {
244                         continue;
245                 }
246
247                 /* filter by partial_attribute_set */
248                 if (partial_attribute_set && !check_partial_attribute_set(sa, partial_attribute_set)) {
249                         continue;
250                 }
251
252                 obj->meta_data_ctr->meta_data[n].originating_change_time = md.ctr.ctr1.array[i].originating_change_time;
253                 obj->meta_data_ctr->meta_data[n].version = md.ctr.ctr1.array[i].version;
254                 obj->meta_data_ctr->meta_data[n].originating_invocation_id = md.ctr.ctr1.array[i].originating_invocation_id;
255                 obj->meta_data_ctr->meta_data[n].originating_usn = md.ctr.ctr1.array[i].originating_usn;
256                 attids[n] = md.ctr.ctr1.array[i].attid;
257                 n++;
258         }
259
260         /* ignore it if its an empty change. Note that renames always
261          * change the 'name' attribute, so they won't be ignored by
262          * this */
263         if (n == 0 ||
264             (n == 1 && attids[0] == DRSUAPI_ATTRIBUTE_instanceType)) {
265                 talloc_free(obj->meta_data_ctr);
266                 obj->meta_data_ctr = NULL;
267                 return WERR_OK;
268         }
269
270         obj->meta_data_ctr->count = n;
271
272         obj->object.flags = DRSUAPI_DS_REPLICA_OBJECT_FROM_MASTER;
273         obj->object.attribute_ctr.num_attributes = obj->meta_data_ctr->count;
274         obj->object.attribute_ctr.attributes = talloc_array(obj, struct drsuapi_DsReplicaAttribute,
275                                                             obj->object.attribute_ctr.num_attributes);
276
277         /*
278          * Note that the meta_data array and the attributes array must
279          * be the same size and in the same order
280          */
281         for (i=0; i<obj->object.attribute_ctr.num_attributes; i++) {
282                 struct ldb_message_element *el;
283                 WERROR werr;
284                 const struct dsdb_attribute *sa;
285         
286                 sa = dsdb_attribute_by_attributeID_id(schema, attids[i]);
287                 if (!sa) {
288                         DEBUG(0,("Unable to find attributeID %u in schema\n", attids[i]));
289                         return WERR_DS_DRA_INTERNAL_ERROR;
290                 }
291
292                 el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
293                 if (el == NULL) {
294                         /* this happens for attributes that have been removed */
295                         DEBUG(5,("No element '%s' for attributeID %u in message\n",
296                                  sa->lDAPDisplayName, attids[i]));
297                         ZERO_STRUCT(obj->object.attribute_ctr.attributes[i]);
298                         obj->object.attribute_ctr.attributes[i].attid =
299                                         dsdb_attribute_get_attid(sa, syntax_ctx.is_schema_nc);
300                 } else {
301                         werr = sa->syntax->ldb_to_drsuapi(&syntax_ctx, sa, el, obj,
302                                                           &obj->object.attribute_ctr.attributes[i]);
303                         if (!W_ERROR_IS_OK(werr)) {
304                                 DEBUG(0,("Unable to convert %s to DRS object - %s\n", 
305                                          sa->lDAPDisplayName, win_errstr(werr)));
306                                 return werr;
307                         }
308                         /* if DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING is set
309                          * check if attribute is secret and send a null value
310                          */
311                         if (replica_flags & DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING) {
312                                 drsuapi_process_secret_attribute(&obj->object.attribute_ctr.attributes[i],
313                                                                  &obj->meta_data_ctr->meta_data[i]);
314                         }
315                         /* some attributes needs to be encrypted
316                            before being sent */
317                         werr = drsuapi_encrypt_attribute(obj, session_key, rid, 
318                                                          &obj->object.attribute_ctr.attributes[i]);
319                         if (!W_ERROR_IS_OK(werr)) {
320                                 DEBUG(0,("Unable to encrypt %s in DRS object - %s\n", 
321                                          sa->lDAPDisplayName, win_errstr(werr)));
322                                 return werr;
323                         }
324                 }
325         }
326
327         return WERR_OK;
328 }
329
330
331 /*
332   add one linked attribute from an object to the list of linked
333   attributes in a getncchanges request
334  */
335 static WERROR get_nc_changes_add_la(TALLOC_CTX *mem_ctx,
336                                     struct ldb_context *sam_ctx,
337                                     const struct dsdb_schema *schema,
338                                     const struct dsdb_attribute *sa,
339                                     struct ldb_message *msg,
340                                     struct dsdb_dn *dsdb_dn,
341                                     struct drsuapi_DsReplicaLinkedAttribute **la_list,
342                                     uint32_t *la_count)
343 {
344         struct drsuapi_DsReplicaLinkedAttribute *la;
345         bool active;
346         NTSTATUS status;
347         WERROR werr;
348
349         (*la_list) = talloc_realloc(mem_ctx, *la_list, struct drsuapi_DsReplicaLinkedAttribute, (*la_count)+1);
350         W_ERROR_HAVE_NO_MEMORY(*la_list);
351
352         la = &(*la_list)[*la_count];
353
354         la->identifier = get_object_identifier(*la_list, msg);
355         W_ERROR_HAVE_NO_MEMORY(la->identifier);
356
357         active = (dsdb_dn_rmd_flags(dsdb_dn->dn) & DSDB_RMD_FLAG_DELETED) == 0;
358
359         la->attid = sa->attributeID_id;
360         la->flags = active?DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE:0;
361
362         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->originating_add_time, "RMD_ADDTIME");
363         if (!NT_STATUS_IS_OK(status)) {
364                 return ntstatus_to_werror(status);
365         }
366         status = dsdb_get_extended_dn_uint32(dsdb_dn->dn, &la->meta_data.version, "RMD_VERSION");
367         if (!NT_STATUS_IS_OK(status)) {
368                 return ntstatus_to_werror(status);
369         }
370         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->meta_data.originating_change_time, "RMD_CHANGETIME");
371         if (!NT_STATUS_IS_OK(status)) {
372                 return ntstatus_to_werror(status);
373         }
374         status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &la->meta_data.originating_invocation_id, "RMD_INVOCID");
375         if (!NT_STATUS_IS_OK(status)) {
376                 return ntstatus_to_werror(status);
377         }
378         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &la->meta_data.originating_usn, "RMD_ORIGINATING_USN");
379         if (!NT_STATUS_IS_OK(status)) {
380                 return ntstatus_to_werror(status);
381         }
382
383         werr = dsdb_dn_la_to_blob(sam_ctx, sa, schema, *la_list, dsdb_dn, &la->value.blob);
384         W_ERROR_NOT_OK_RETURN(werr);
385
386         (*la_count)++;
387         return WERR_OK;
388 }
389
390
391 /*
392   add linked attributes from an object to the list of linked
393   attributes in a getncchanges request
394  */
395 static WERROR get_nc_changes_add_links(struct ldb_context *sam_ctx,
396                                        TALLOC_CTX *mem_ctx,
397                                        struct ldb_dn *ncRoot_dn,
398                                        struct dsdb_schema *schema,
399                                        uint64_t highest_usn,
400                                        uint32_t replica_flags,
401                                        struct ldb_message *msg,
402                                        struct drsuapi_DsReplicaLinkedAttribute **la_list,
403                                        uint32_t *la_count,
404                                        struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector)
405 {
406         unsigned int i;
407         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
408         uint64_t uSNChanged = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
409
410         for (i=0; i<msg->num_elements; i++) {
411                 struct ldb_message_element *el = &msg->elements[i];
412                 const struct dsdb_attribute *sa;
413                 unsigned int j;
414
415                 sa = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
416
417                 if (!sa || sa->linkID == 0 || (sa->linkID & 1)) {
418                         /* we only want forward links */
419                         continue;
420                 }
421
422                 if (el->num_values && !dsdb_dn_is_upgraded_link_val(&el->values[0])) {
423                         /* its an old style link, it will have been
424                          * sent in the main replication data */
425                         continue;
426                 }
427
428                 for (j=0; j<el->num_values; j++) {
429                         struct dsdb_dn *dsdb_dn;
430                         uint64_t local_usn;
431                         NTSTATUS status;
432                         WERROR werr;
433
434                         dsdb_dn = dsdb_dn_parse(tmp_ctx, sam_ctx, &el->values[j], sa->syntax->ldap_oid);
435                         if (dsdb_dn == NULL) {
436                                 DEBUG(1,(__location__ ": Failed to parse DN for %s in %s\n",
437                                          el->name, ldb_dn_get_linearized(msg->dn)));
438                                 talloc_free(tmp_ctx);
439                                 return WERR_DS_DRA_INTERNAL_ERROR;
440                         }
441
442                         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &local_usn, "RMD_LOCAL_USN");
443                         if (!NT_STATUS_IS_OK(status)) {
444                                 /* this can happen for attributes
445                                    given to us with old style meta
446                                    data */
447                                 continue;
448                         }
449
450                         if (local_usn > uSNChanged) {
451                                 DEBUG(1,(__location__ ": uSNChanged less than RMD_LOCAL_USN for %s on %s\n",
452                                          el->name, ldb_dn_get_linearized(msg->dn)));
453                                 talloc_free(tmp_ctx);
454                                 return WERR_DS_DRA_INTERNAL_ERROR;
455                         }
456
457                         if (local_usn < highest_usn) {
458                                 continue;
459                         }
460
461                         werr = get_nc_changes_add_la(mem_ctx, sam_ctx, schema, sa, msg,
462                                                      dsdb_dn, la_list, la_count);
463                         if (!W_ERROR_IS_OK(werr)) {
464                                 talloc_free(tmp_ctx);
465                                 return werr;
466                         }
467                 }
468         }
469
470         talloc_free(tmp_ctx);
471         return WERR_OK;
472 }
473
474 /*
475   fill in the cursors return based on the replUpToDateVector for the ncRoot_dn
476  */
477 static WERROR get_nc_changes_udv(struct ldb_context *sam_ctx,
478                                  struct ldb_dn *ncRoot_dn,
479                                  struct drsuapi_DsReplicaCursor2CtrEx *udv)
480 {
481         int ret;
482
483         udv->version = 2;
484         udv->reserved1 = 0;
485         udv->reserved2 = 0;
486
487         ret = dsdb_load_udv_v2(sam_ctx, ncRoot_dn, udv, &udv->cursors, &udv->count);
488         if (ret != LDB_SUCCESS) {
489                 DEBUG(0,(__location__ ": Failed to load UDV for %s - %s\n",
490                          ldb_dn_get_linearized(ncRoot_dn), ldb_errstring(sam_ctx)));
491                 return WERR_DS_DRA_INTERNAL_ERROR;
492         }
493         
494         return WERR_OK;
495 }
496
497
498 /* comparison function for linked attributes - see CompareLinks() in
499  * MS-DRSR section 4.1.10.5.17 */
500 static int linked_attribute_compare(const struct drsuapi_DsReplicaLinkedAttribute *la1,
501                                     const struct drsuapi_DsReplicaLinkedAttribute *la2,
502                                     struct ldb_context *sam_ctx)
503 {
504         int c;
505         WERROR werr;
506         TALLOC_CTX *tmp_ctx;
507         const struct dsdb_schema *schema;
508         const struct dsdb_attribute *schema_attrib;
509         struct dsdb_dn *dn1, *dn2;
510         struct GUID guid1, guid2;
511         NTSTATUS status;
512
513         c = GUID_compare(&la1->identifier->guid,
514                          &la2->identifier->guid);
515         if (c != 0) return c;
516
517         if (la1->attid != la2->attid) {
518                 return la1->attid < la2->attid? -1:1;
519         }
520
521         if ((la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE) !=
522             (la2->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)) {
523                 return (la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)? 1:-1;
524         }
525
526         /* we need to get the target GUIDs to compare */
527         tmp_ctx = talloc_new(sam_ctx);
528
529         schema = dsdb_get_schema(sam_ctx, tmp_ctx);
530         schema_attrib = dsdb_attribute_by_attributeID_id(schema, la1->attid);
531
532         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la1->value.blob, &dn1);
533         if (!W_ERROR_IS_OK(werr)) {
534                 DEBUG(0,(__location__ ": Bad la1 blob in sort\n"));
535                 talloc_free(tmp_ctx);
536                 return 0;
537         }
538
539         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la2->value.blob, &dn2);
540         if (!W_ERROR_IS_OK(werr)) {
541                 DEBUG(0,(__location__ ": Bad la2 blob in sort\n"));
542                 talloc_free(tmp_ctx);
543                 return 0;
544         }
545
546         status = dsdb_get_extended_dn_guid(dn1->dn, &guid1, "GUID");
547         if (!NT_STATUS_IS_OK(status)) {
548                 DEBUG(0,(__location__ ": Bad la1 guid in sort\n"));
549                 talloc_free(tmp_ctx);
550                 return 0;
551         }
552         status = dsdb_get_extended_dn_guid(dn2->dn, &guid2, "GUID");
553         if (!NT_STATUS_IS_OK(status)) {
554                 DEBUG(0,(__location__ ": Bad la2 guid in sort\n"));
555                 talloc_free(tmp_ctx);
556                 return 0;
557         }
558
559         talloc_free(tmp_ctx);
560
561         return GUID_compare(&guid1, &guid2);
562 }
563
564
565 /*
566   sort the objects we send by tree order
567  */
568 static int site_res_cmp_parent_order(struct ldb_message **m1, struct ldb_message **m2)
569 {
570         return ldb_dn_compare((*m2)->dn, (*m1)->dn);
571 }
572
573 /*
574   sort the objects we send first by uSNChanged
575  */
576 static int site_res_cmp_usn_order(struct ldb_message **m1, struct ldb_message **m2)
577 {
578         unsigned usnchanged1, usnchanged2;
579         unsigned cn1, cn2;
580         cn1 = ldb_dn_get_comp_num((*m1)->dn);
581         cn2 = ldb_dn_get_comp_num((*m2)->dn);
582         if (cn1 != cn2) {
583                 return cn1 > cn2 ? 1 : -1;
584         }
585         usnchanged1 = ldb_msg_find_attr_as_uint(*m1, "uSNChanged", 0);
586         usnchanged2 = ldb_msg_find_attr_as_uint(*m2, "uSNChanged", 0);
587         if (usnchanged1 == usnchanged2) {
588                 return 0;
589         }
590         return usnchanged1 > usnchanged2 ? 1 : -1;
591 }
592
593
594 /*
595   handle a DRSUAPI_EXOP_FSMO_RID_ALLOC call
596  */
597 static WERROR getncchanges_rid_alloc(struct drsuapi_bind_state *b_state,
598                                      TALLOC_CTX *mem_ctx,
599                                      struct drsuapi_DsGetNCChangesRequest8 *req8,
600                                      struct drsuapi_DsGetNCChangesCtr6 *ctr6)
601 {
602         struct ldb_dn *rid_manager_dn, *fsmo_role_dn, *req_dn;
603         int ret;
604         struct ldb_context *ldb = b_state->sam_ctx;
605         struct ldb_result *ext_res;
606         struct ldb_dn *base_dn;
607         struct dsdb_fsmo_extended_op *exop;
608
609         /*
610           steps:
611             - verify that the DN being asked for is the RID Manager DN
612             - verify that we are the RID Manager
613          */
614
615         /* work out who is the RID Manager */
616         ret = samdb_rid_manager_dn(ldb, mem_ctx, &rid_manager_dn);
617         if (ret != LDB_SUCCESS) {
618                 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s\n", ldb_errstring(ldb)));
619                 return WERR_DS_DRA_INTERNAL_ERROR;
620         }
621
622         req_dn = drs_ObjectIdentifier_to_dn(mem_ctx, ldb, req8->naming_context);
623         if (!req_dn ||
624             !ldb_dn_validate(req_dn) ||
625             ldb_dn_compare(req_dn, rid_manager_dn) != 0) {
626                 /* that isn't the RID Manager DN */
627                 DEBUG(0,(__location__ ": RID Alloc request for wrong DN %s\n",
628                          drs_ObjectIdentifier_to_string(mem_ctx, req8->naming_context)));
629                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_MISMATCH;
630                 return WERR_OK;
631         }
632
633         /* find the DN of the RID Manager */
634         ret = samdb_reference_dn(ldb, mem_ctx, rid_manager_dn, "fSMORoleOwner", &fsmo_role_dn);
635         if (ret != LDB_SUCCESS) {
636                 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s\n",
637                          ldb_errstring(ldb)));
638                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
639                 return WERR_DS_DRA_INTERNAL_ERROR;
640         }
641
642         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), fsmo_role_dn) != 0) {
643                 /* we're not the RID Manager - go away */
644                 DEBUG(0,(__location__ ": RID Alloc request when not RID Manager\n"));
645                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
646                 return WERR_OK;
647         }
648
649         exop = talloc(mem_ctx, struct dsdb_fsmo_extended_op);
650         W_ERROR_HAVE_NO_MEMORY(exop);
651
652         exop->fsmo_info = req8->fsmo_info;
653         exop->destination_dsa_guid = req8->destination_dsa_guid;
654
655         ret = ldb_transaction_start(ldb);
656         if (ret != LDB_SUCCESS) {
657                 DEBUG(0,(__location__ ": Failed transaction start - %s\n",
658                          ldb_errstring(ldb)));
659                 return WERR_DS_DRA_INTERNAL_ERROR;
660         }
661
662         /*
663          * FIXME (kim): this is a temp hack to return just few object,
664          * but not the whole domain NC.
665          * We should remove this hack and implement a 'scope'
666          * building function to return just the set of object
667          * documented for DRSUAPI_EXOP_FSMO_RID_ALLOC extended_op
668          */
669         ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &req8->highwatermark.highest_usn);
670
671         ret = ldb_extended(ldb, DSDB_EXTENDED_ALLOCATE_RID_POOL, exop, &ext_res);
672         if (ret != LDB_SUCCESS) {
673                 DEBUG(0,(__location__ ": Failed extended allocation RID pool operation - %s\n",
674                          ldb_errstring(ldb)));
675                 ldb_transaction_cancel(ldb);
676                 return WERR_DS_DRA_INTERNAL_ERROR;
677         }
678
679         ret = ldb_transaction_commit(ldb);
680         if (ret != LDB_SUCCESS) {
681                 DEBUG(0,(__location__ ": Failed transaction commit - %s\n",
682                          ldb_errstring(ldb)));
683                 return WERR_DS_DRA_INTERNAL_ERROR;
684         }
685
686         talloc_free(ext_res);
687
688         base_dn = ldb_get_default_basedn(ldb);
689
690         DEBUG(2,("Allocated RID pool for server %s\n",
691                  GUID_string(mem_ctx, &req8->destination_dsa_guid)));
692
693         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
694
695         return WERR_OK;
696 }
697
698 /*
699   return an array of SIDs from a ldb_message given an attribute name
700   assumes the SIDs are in extended DN format
701  */
702 static WERROR samdb_result_sid_array_dn(struct ldb_context *sam_ctx,
703                                         struct ldb_message *msg,
704                                         TALLOC_CTX *mem_ctx,
705                                         const char *attr,
706                                         const struct dom_sid ***sids)
707 {
708         struct ldb_message_element *el;
709         unsigned int i;
710
711         el = ldb_msg_find_element(msg, attr);
712         if (!el) {
713                 *sids = NULL;
714                 return WERR_OK;
715         }
716
717         (*sids) = talloc_array(mem_ctx, const struct dom_sid *, el->num_values + 1);
718         W_ERROR_HAVE_NO_MEMORY(*sids);
719
720         for (i=0; i<el->num_values; i++) {
721                 struct ldb_dn *dn = ldb_dn_from_ldb_val(mem_ctx, sam_ctx, &el->values[i]);
722                 NTSTATUS status;
723                 struct dom_sid *sid;
724
725                 sid = talloc(*sids, struct dom_sid);
726                 W_ERROR_HAVE_NO_MEMORY(sid);
727                 status = dsdb_get_extended_dn_sid(dn, sid, "SID");
728                 if (!NT_STATUS_IS_OK(status)) {
729                         return WERR_INTERNAL_DB_CORRUPTION;
730                 }
731                 (*sids)[i] = sid;
732         }
733         (*sids)[i] = NULL;
734
735         return WERR_OK;
736 }
737
738
739 /*
740   return an array of SIDs from a ldb_message given an attribute name
741   assumes the SIDs are in NDR form
742  */
743 static WERROR samdb_result_sid_array_ndr(struct ldb_context *sam_ctx,
744                                          struct ldb_message *msg,
745                                          TALLOC_CTX *mem_ctx,
746                                          const char *attr,
747                                          const struct dom_sid ***sids)
748 {
749         struct ldb_message_element *el;
750         unsigned int i;
751
752         el = ldb_msg_find_element(msg, attr);
753         if (!el) {
754                 *sids = NULL;
755                 return WERR_OK;
756         }
757
758         (*sids) = talloc_array(mem_ctx, const struct dom_sid *, el->num_values + 1);
759         W_ERROR_HAVE_NO_MEMORY(*sids);
760
761         for (i=0; i<el->num_values; i++) {
762                 enum ndr_err_code ndr_err;
763                 struct dom_sid *sid;
764
765                 sid = talloc(*sids, struct dom_sid);
766                 W_ERROR_HAVE_NO_MEMORY(sid);
767
768                 ndr_err = ndr_pull_struct_blob(&el->values[i], sid, sid,
769                                                (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
770                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
771                         return WERR_INTERNAL_DB_CORRUPTION;
772                 }
773                 (*sids)[i] = sid;
774         }
775         (*sids)[i] = NULL;
776
777         return WERR_OK;
778 }
779
780 /*
781   see if any SIDs in list1 are in list2
782  */
783 static bool sid_list_match(const struct dom_sid **list1, const struct dom_sid **list2)
784 {
785         unsigned int i, j;
786         /* do we ever have enough SIDs here to worry about O(n^2) ? */
787         for (i=0; list1[i]; i++) {
788                 for (j=0; list2[j]; j++) {
789                         if (dom_sid_equal(list1[i], list2[j])) {
790                                 return true;
791                         }
792                 }
793         }
794         return false;
795 }
796
797 /*
798   handle a DRSUAPI_EXOP_REPL_SECRET call
799  */
800 static WERROR getncchanges_repl_secret(struct drsuapi_bind_state *b_state,
801                                        TALLOC_CTX *mem_ctx,
802                                        struct drsuapi_DsGetNCChangesRequest8 *req8,
803                                        struct dom_sid *user_sid,
804                                        struct drsuapi_DsGetNCChangesCtr6 *ctr6)
805 {
806         struct drsuapi_DsReplicaObjectIdentifier *ncRoot = req8->naming_context;
807         struct ldb_dn *obj_dn, *rodc_dn, *krbtgt_link_dn;
808         int ret;
809         const char *rodc_attrs[] = { "msDS-KrbTgtLink", "msDS-NeverRevealGroup", "msDS-RevealOnDemandGroup", NULL };
810         const char *obj_attrs[] = { "tokenGroups", "objectSid", "UserAccountControl", "msDS-KrbTgtLinkBL", NULL };
811         struct ldb_result *rodc_res, *obj_res;
812         const struct dom_sid **never_reveal_sids, **reveal_sids, **token_sids;
813         WERROR werr;
814
815         DEBUG(3,(__location__ ": DRSUAPI_EXOP_REPL_SECRET extended op on %s\n",
816                  drs_ObjectIdentifier_to_string(mem_ctx, ncRoot)));
817
818         /*
819          * we need to work out if we will allow this RODC to
820          * replicate the secrets for this object
821          *
822          * see 4.1.10.5.14 GetRevealSecretsPolicyForUser for details
823          * of this function
824          */
825
826         if (b_state->sam_ctx_system == NULL) {
827                 /* this operation needs system level access */
828                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_ACCESS_DENIED;
829                 return WERR_DS_DRA_SOURCE_DISABLED;
830         }
831
832         obj_dn = drs_ObjectIdentifier_to_dn(mem_ctx, b_state->sam_ctx_system, ncRoot);
833         if (!ldb_dn_validate(obj_dn)) goto failed;
834
835         rodc_dn = ldb_dn_new_fmt(mem_ctx, b_state->sam_ctx_system, "<SID=%s>",
836                                  dom_sid_string(mem_ctx, user_sid));
837         if (!ldb_dn_validate(rodc_dn)) goto failed;
838
839         /* do the two searches we need */
840         ret = dsdb_search_dn(b_state->sam_ctx_system, mem_ctx, &rodc_res, rodc_dn, rodc_attrs,
841                              DSDB_SEARCH_SHOW_EXTENDED_DN);
842         if (ret != LDB_SUCCESS || rodc_res->count != 1) goto failed;
843
844         ret = dsdb_search_dn(b_state->sam_ctx_system, mem_ctx, &obj_res, obj_dn, obj_attrs, 0);
845         if (ret != LDB_SUCCESS || obj_res->count != 1) goto failed;
846
847         /* if the object SID is equal to the user_sid, allow */
848         if (dom_sid_equal(user_sid,
849                           samdb_result_dom_sid(mem_ctx, obj_res->msgs[0], "objectSid"))) {
850                 goto allowed;
851         }
852
853         /* an RODC is allowed to get its own krbtgt account secrets */
854         krbtgt_link_dn = samdb_result_dn(b_state->sam_ctx_system, mem_ctx,
855                                          rodc_res->msgs[0], "msDS-KrbTgtLink", NULL);
856         if (krbtgt_link_dn != NULL &&
857             ldb_dn_compare(obj_dn, krbtgt_link_dn) == 0) {
858                 goto allowed;
859         }
860
861         /* but it isn't allowed to get anyone elses krbtgt secrets */
862         if (samdb_result_dn(b_state->sam_ctx_system, mem_ctx,
863                             obj_res->msgs[0], "msDS-KrbTgtLinkBL", NULL)) {
864                 goto denied;
865         }
866
867         if (samdb_result_uint(obj_res->msgs[0], "UserAccountControl", 0) &
868             UF_INTERDOMAIN_TRUST_ACCOUNT) {
869                 goto denied;
870         }
871
872         werr = samdb_result_sid_array_dn(b_state->sam_ctx_system, rodc_res->msgs[0],
873                                          mem_ctx, "msDS-NeverRevealGroup", &never_reveal_sids);
874         if (!W_ERROR_IS_OK(werr)) {
875                 goto denied;
876         }
877
878         werr = samdb_result_sid_array_dn(b_state->sam_ctx_system, rodc_res->msgs[0],
879                                          mem_ctx, "msDS-RevealOnDemandGroup", &reveal_sids);
880         if (!W_ERROR_IS_OK(werr)) {
881                 goto denied;
882         }
883
884         werr = samdb_result_sid_array_ndr(b_state->sam_ctx_system, obj_res->msgs[0],
885                                          mem_ctx, "tokenGroups", &token_sids);
886         if (!W_ERROR_IS_OK(werr) || token_sids==NULL) {
887                 goto denied;
888         }
889
890         if (never_reveal_sids &&
891             sid_list_match(token_sids, never_reveal_sids)) {
892                 goto denied;
893         }
894
895         if (reveal_sids &&
896             sid_list_match(token_sids, reveal_sids)) {
897                 goto allowed;
898         }
899
900         /* default deny */
901 denied:
902         DEBUG(2,(__location__ ": Denied RODC secret replication for %s by RODC %s\n",
903                  ldb_dn_get_linearized(obj_dn), ldb_dn_get_linearized(rodc_res->msgs[0]->dn)));
904         ctr6->extended_ret = DRSUAPI_EXOP_ERR_NONE;
905         return WERR_DS_DRA_ACCESS_DENIED;
906
907 allowed:
908         DEBUG(2,(__location__ ": Allowed RODC secret replication for %s by RODC %s\n",
909                  ldb_dn_get_linearized(obj_dn), ldb_dn_get_linearized(rodc_res->msgs[0]->dn)));
910         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
911         req8->highwatermark.highest_usn = 0;
912         return WERR_OK;
913
914 failed:
915         DEBUG(2,(__location__ ": Failed RODC secret replication for %s by RODC %s\n",
916                  ldb_dn_get_linearized(obj_dn), dom_sid_string(mem_ctx, user_sid)));
917         ctr6->extended_ret = DRSUAPI_EXOP_ERR_NONE;
918         return WERR_DS_DRA_BAD_DN;
919 }
920
921
922 /*
923   handle a DRSUAPI_EXOP_REPL_OBJ call
924  */
925 static WERROR getncchanges_repl_obj(struct drsuapi_bind_state *b_state,
926                                     TALLOC_CTX *mem_ctx,
927                                     struct drsuapi_DsGetNCChangesRequest8 *req8,
928                                     struct dom_sid *user_sid,
929                                     struct drsuapi_DsGetNCChangesCtr6 *ctr6)
930 {
931         struct drsuapi_DsReplicaObjectIdentifier *ncRoot = req8->naming_context;
932
933         DEBUG(3,(__location__ ": DRSUAPI_EXOP_REPL_OBJ extended op on %s\n",
934                  drs_ObjectIdentifier_to_string(mem_ctx, ncRoot)));
935
936         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
937         req8->highwatermark.highest_usn = 0;
938         return WERR_OK;
939 }
940
941
942 /*
943   handle DRSUAPI_EXOP_FSMO_REQ_ROLE,
944   DRSUAPI_EXOP_FSMO_RID_REQ_ROLE,
945   and DRSUAPI_EXOP_FSMO_REQ_PDC calls
946  */
947 static WERROR getncchanges_change_master(struct drsuapi_bind_state *b_state,
948                                          TALLOC_CTX *mem_ctx,
949                                          struct drsuapi_DsGetNCChangesRequest8 *req8,
950                                          struct drsuapi_DsGetNCChangesCtr6 *ctr6)
951 {
952         struct ldb_dn *fsmo_role_dn, *req_dn, *ntds_dn;
953         int ret;
954         unsigned int i;
955         struct ldb_context *ldb = b_state->sam_ctx;
956         struct ldb_message *msg;
957
958         /*
959           steps:
960             - verify that the client dn exists
961             - verify that we are the current master
962          */
963
964         req_dn = drs_ObjectIdentifier_to_dn(mem_ctx, ldb, req8->naming_context);
965         if (!req_dn ||
966             !ldb_dn_validate(req_dn)) {
967                 /* that is not a valid dn */
968                 DEBUG(0,(__location__ ": FSMO role transfer request for invalid DN %s\n",
969                          drs_ObjectIdentifier_to_string(mem_ctx, req8->naming_context)));
970                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_MISMATCH;
971                 return WERR_OK;
972         }
973
974         /* retrieve the current role owner */
975         ret = samdb_reference_dn(ldb, mem_ctx, req_dn, "fSMORoleOwner", &fsmo_role_dn);
976         if (ret != LDB_SUCCESS) {
977                 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in context - %s\n",
978                          ldb_errstring(ldb)));
979                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
980                 return WERR_DS_DRA_INTERNAL_ERROR;
981         }
982
983         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), fsmo_role_dn) != 0) {
984                 /* we're not the current owner - go away */
985                 DEBUG(0,(__location__ ": FSMO transfer request when not owner\n"));
986                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
987                 return WERR_OK;
988         }
989
990         /* change the current master */
991         msg = ldb_msg_new(ldb);
992         W_ERROR_HAVE_NO_MEMORY(msg);
993         msg->dn = drs_ObjectIdentifier_to_dn(msg, ldb, req8->naming_context);
994         W_ERROR_HAVE_NO_MEMORY(msg->dn);
995
996         ret = dsdb_find_dn_by_guid(ldb, msg, &req8->destination_dsa_guid, &ntds_dn);
997         if (ret != LDB_SUCCESS) {
998                 DEBUG(0, (__location__ ": Unable to find NTDS object for guid %s - %s\n",
999                           GUID_string(mem_ctx, &req8->destination_dsa_guid), ldb_errstring(ldb)));
1000                 talloc_free(msg);
1001                 return WERR_DS_DRA_INTERNAL_ERROR;
1002         }
1003
1004         ret = ldb_msg_add_string(msg, "fSMORoleOwner", ldb_dn_get_linearized(ntds_dn));
1005         if (ret != 0) {
1006                 talloc_free(msg);
1007                 return WERR_DS_DRA_INTERNAL_ERROR;
1008         }
1009
1010         for (i=0;i<msg->num_elements;i++) {
1011                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
1012         }
1013
1014         ret = ldb_transaction_start(ldb);
1015         if (ret != LDB_SUCCESS) {
1016                 DEBUG(0,(__location__ ": Failed transaction start - %s\n",
1017                          ldb_errstring(ldb)));
1018                 return WERR_DS_DRA_INTERNAL_ERROR;
1019         }
1020
1021         ret = ldb_modify(ldb, msg);
1022         if (ret != LDB_SUCCESS) {
1023                 DEBUG(0,(__location__ ": Failed to change current owner - %s\n",
1024                          ldb_errstring(ldb)));
1025                 ldb_transaction_cancel(ldb);
1026                 return WERR_DS_DRA_INTERNAL_ERROR;
1027         }
1028
1029         ret = ldb_transaction_commit(ldb);
1030         if (ret != LDB_SUCCESS) {
1031                 DEBUG(0,(__location__ ": Failed transaction commit - %s\n",
1032                          ldb_errstring(ldb)));
1033                 return WERR_DS_DRA_INTERNAL_ERROR;
1034         }
1035
1036         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
1037
1038         return WERR_OK;
1039 }
1040
1041 /* state of a partially completed getncchanges call */
1042 struct drsuapi_getncchanges_state {
1043         struct ldb_result *site_res;
1044         uint32_t num_sent;
1045         struct ldb_dn *ncRoot_dn;
1046         bool is_schema_nc;
1047         uint64_t min_usn;
1048         uint64_t highest_usn;
1049         struct ldb_dn *last_dn;
1050         struct drsuapi_DsReplicaLinkedAttribute *la_list;
1051         uint32_t la_count;
1052         bool la_sorted;
1053         uint32_t la_idx;
1054         struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector;
1055 };
1056
1057 /*
1058   see if this getncchanges request includes a request to reveal secret information
1059  */
1060 static WERROR dcesrv_drsuapi_is_reveal_secrets_request(struct drsuapi_bind_state *b_state,
1061                                                        struct drsuapi_DsGetNCChangesRequest8 *req8,
1062                                                        bool *is_secret_request)
1063 {
1064         enum drsuapi_DsExtendedOperation exop;
1065         int i;
1066         struct dsdb_schema *schema;
1067
1068         *is_secret_request = true;
1069
1070         exop = req8->extended_op;
1071
1072         switch (exop) {
1073         case DRSUAPI_EXOP_FSMO_REQ_ROLE:
1074         case DRSUAPI_EXOP_FSMO_RID_ALLOC:
1075         case DRSUAPI_EXOP_FSMO_RID_REQ_ROLE:
1076         case DRSUAPI_EXOP_FSMO_REQ_PDC:
1077         case DRSUAPI_EXOP_FSMO_ABANDON_ROLE:
1078                 /* FSMO exops can reveal secrets */
1079                 *is_secret_request = true;
1080                 return WERR_OK;
1081         case DRSUAPI_EXOP_REPL_SECRET:
1082         case DRSUAPI_EXOP_REPL_OBJ:
1083         case DRSUAPI_EXOP_NONE:
1084                 break;
1085         }
1086
1087         if (req8->replica_flags & DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING) {
1088                 *is_secret_request = false;
1089                 return WERR_OK;
1090         }
1091
1092         if (exop == DRSUAPI_EXOP_REPL_SECRET ||
1093             req8->partial_attribute_set == NULL) {
1094                 /* they want secrets */
1095                 *is_secret_request = true;
1096                 return WERR_OK;
1097         }
1098
1099         schema = dsdb_get_schema(b_state->sam_ctx, NULL);
1100
1101         /* check the attributes they asked for */
1102         for (i=0; i<req8->partial_attribute_set->num_attids; i++) {
1103                 const struct dsdb_attribute *sa;
1104                 sa = dsdb_attribute_by_attributeID_id(schema, req8->partial_attribute_set->attids[i]);
1105                 if (sa == NULL) {
1106                         return WERR_DS_DRA_SCHEMA_MISMATCH;
1107                 }
1108                 if (!dsdb_attr_in_rodc_fas(sa)) {
1109                         *is_secret_request = true;
1110                         return WERR_OK;
1111                 }
1112         }
1113
1114         /* check the attributes they asked for */
1115         for (i=0; i<req8->partial_attribute_set_ex->num_attids; i++) {
1116                 const struct dsdb_attribute *sa;
1117                 sa = dsdb_attribute_by_attributeID_id(schema, req8->partial_attribute_set_ex->attids[i]);
1118                 if (sa == NULL) {
1119                         return WERR_DS_DRA_SCHEMA_MISMATCH;
1120                 }
1121                 if (!dsdb_attr_in_rodc_fas(sa)) {
1122                         *is_secret_request = true;
1123                         return WERR_OK;
1124                 }
1125         }
1126
1127         *is_secret_request = false;
1128         return WERR_OK;
1129 }
1130
1131
1132
1133 /* 
1134   drsuapi_DsGetNCChanges
1135
1136   see MS-DRSR 4.1.10.5.2 for basic logic of this function
1137 */
1138 WERROR dcesrv_drsuapi_DsGetNCChanges(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1139                                      struct drsuapi_DsGetNCChanges *r)
1140 {
1141         struct drsuapi_DsReplicaObjectIdentifier *ncRoot;
1142         int ret;
1143         unsigned int i;
1144         struct dsdb_schema *schema;
1145         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
1146         struct drsuapi_DsReplicaObjectListItemEx **currentObject;
1147         NTSTATUS status;
1148         DATA_BLOB session_key;
1149         const char *attrs[] = { "*", "distinguishedName",
1150                                 "nTSecurityDescriptor",
1151                                 "parentGUID",
1152                                 "replPropertyMetaData",
1153                                 "unicodePwd",
1154                                 "dBCSPwd",
1155                                 "ntPwdHistory",
1156                                 "lmPwdHistory",
1157                                 "supplementalCredentials",
1158                                 NULL };
1159         WERROR werr;
1160         struct dcesrv_handle *h;
1161         struct drsuapi_bind_state *b_state;     
1162         struct drsuapi_getncchanges_state *getnc_state;
1163         struct drsuapi_DsGetNCChangesRequest8 *req8;
1164         uint32_t options;
1165         uint32_t max_objects;
1166         uint32_t max_links;
1167         uint32_t link_count = 0;
1168         uint32_t link_total = 0;
1169         uint32_t link_given = 0;
1170         struct ldb_dn *search_dn = NULL;
1171         bool am_rodc, null_scope=false;
1172         enum security_user_level security_level;
1173         struct ldb_context *sam_ctx;
1174         struct dom_sid *user_sid;
1175         bool is_secret_request;
1176
1177         DCESRV_PULL_HANDLE_WERR(h, r->in.bind_handle, DRSUAPI_BIND_HANDLE);
1178         b_state = h->data;
1179
1180         sam_ctx = b_state->sam_ctx_system?b_state->sam_ctx_system:b_state->sam_ctx;
1181
1182         *r->out.level_out = 6;
1183         /* TODO: linked attributes*/
1184         r->out.ctr->ctr6.linked_attributes_count = 0;
1185         r->out.ctr->ctr6.linked_attributes = NULL;
1186
1187         r->out.ctr->ctr6.object_count = 0;
1188         r->out.ctr->ctr6.nc_object_count = 0;
1189         r->out.ctr->ctr6.more_data = false;
1190         r->out.ctr->ctr6.uptodateness_vector = NULL;
1191
1192         /* a RODC doesn't allow for any replication */
1193         ret = samdb_rodc(sam_ctx, &am_rodc);
1194         if (ret == LDB_SUCCESS && am_rodc) {
1195                 DEBUG(0,(__location__ ": DsGetNCChanges attempt on RODC\n"));
1196                 return WERR_DS_DRA_SOURCE_DISABLED;
1197         }
1198
1199         /* Check request revision. 
1200            TODO: Adding mappings to req8 from the other levels
1201          */
1202         if (r->in.level != 8) {
1203                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with unsupported level %u\n",
1204                          r->in.level));
1205                 return WERR_REVISION_MISMATCH;
1206         }
1207
1208         req8 = &r->in.req->req8;
1209
1210         /* Perform access checks. */
1211         /* TODO: we need to support a sync on a specific non-root
1212          * DN. We'll need to find the real partition root here */
1213         ncRoot = req8->naming_context;
1214         if (ncRoot == NULL) {
1215                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with no NC\n"));
1216                 return WERR_DS_DRA_INVALID_PARAMETER;
1217         }
1218
1219         if (samdb_ntds_options(sam_ctx, &options) != LDB_SUCCESS) {
1220                 return WERR_DS_DRA_INTERNAL_ERROR;
1221         }
1222         
1223         if ((options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) &&
1224             !(req8->replica_flags & DRSUAPI_DRS_SYNC_FORCED)) {
1225                 return WERR_DS_DRA_SOURCE_DISABLED;
1226         }
1227
1228         user_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1229
1230         werr = drs_security_access_check_nc_root(b_state->sam_ctx,
1231                                                  mem_ctx,
1232                                                  dce_call->conn->auth_state.session_info->security_token,
1233                                                  req8->naming_context,
1234                                                  GUID_DRS_GET_CHANGES);
1235         if (!W_ERROR_IS_OK(werr)) {
1236                 return werr;
1237         }
1238
1239         werr = dcesrv_drsuapi_is_reveal_secrets_request(b_state, req8, &is_secret_request);
1240         if (!W_ERROR_IS_OK(werr)) {
1241                 return werr;
1242         }
1243         if (is_secret_request && req8->extended_op != DRSUAPI_EXOP_REPL_SECRET) {
1244                 werr = drs_security_access_check_nc_root(b_state->sam_ctx,
1245                                                          mem_ctx,
1246                                                          dce_call->conn->auth_state.session_info->security_token,
1247                                                          req8->naming_context,
1248                                                          GUID_DRS_GET_ALL_CHANGES);
1249                 if (!W_ERROR_IS_OK(werr)) {
1250                         return werr;
1251                 }
1252         }
1253
1254         /* for non-administrator replications, check that they have
1255            given the correct source_dsa_invocation_id */
1256         security_level = security_session_user_level(dce_call->conn->auth_state.session_info,
1257                                                      samdb_domain_sid(sam_ctx));
1258         if (security_level == SECURITY_RO_DOMAIN_CONTROLLER) {
1259                 if (req8->replica_flags & DRSUAPI_DRS_WRIT_REP) {
1260                         /* we rely on this flag being unset for RODC requests */
1261                         req8->replica_flags &= ~DRSUAPI_DRS_WRIT_REP;
1262                 }
1263         }
1264
1265         if (req8->replica_flags & DRSUAPI_DRS_FULL_SYNC_PACKET) {
1266                 /* Ignore the _in_ uptpdateness vector*/
1267                 req8->uptodateness_vector = NULL;
1268         } 
1269
1270         getnc_state = b_state->getncchanges_state;
1271
1272         /* see if a previous replication has been abandoned */
1273         if (getnc_state) {
1274                 struct ldb_dn *new_dn = drs_ObjectIdentifier_to_dn(getnc_state, sam_ctx, ncRoot);
1275                 if (ldb_dn_compare(new_dn, getnc_state->ncRoot_dn) != 0) {
1276                         DEBUG(0,(__location__ ": DsGetNCChanges 2nd replication on different DN %s %s (last_dn %s)\n",
1277                                  ldb_dn_get_linearized(new_dn),
1278                                  ldb_dn_get_linearized(getnc_state->ncRoot_dn),
1279                                  ldb_dn_get_linearized(getnc_state->last_dn)));
1280                         talloc_free(getnc_state);
1281                         getnc_state = NULL;
1282                 }
1283         }
1284
1285         if (getnc_state == NULL) {
1286                 getnc_state = talloc_zero(b_state, struct drsuapi_getncchanges_state);
1287                 if (getnc_state == NULL) {
1288                         return WERR_NOMEM;
1289                 }
1290                 b_state->getncchanges_state = getnc_state;
1291                 getnc_state->ncRoot_dn = drs_ObjectIdentifier_to_dn(getnc_state, sam_ctx, ncRoot);
1292
1293                 /* find out if we are to replicate Schema NC */
1294                 ret = ldb_dn_compare(getnc_state->ncRoot_dn,
1295                                      ldb_get_schema_basedn(b_state->sam_ctx));
1296                 getnc_state->is_schema_nc = (0 == ret);
1297
1298                 /*
1299                  * This is the first replication cycle and it is
1300                  * a good place to handle extended operations
1301                  *
1302                  * FIXME: we don't fully support extended operations yet
1303                  */
1304                 switch (req8->extended_op) {
1305                 case DRSUAPI_EXOP_NONE:
1306                         break;
1307                 case DRSUAPI_EXOP_FSMO_RID_ALLOC:
1308                         werr = getncchanges_rid_alloc(b_state, mem_ctx, req8, &r->out.ctr->ctr6);
1309                         W_ERROR_NOT_OK_RETURN(werr);
1310                         search_dn = ldb_get_default_basedn(sam_ctx);
1311                         break;
1312                 case DRSUAPI_EXOP_REPL_SECRET:
1313                         werr = getncchanges_repl_secret(b_state, mem_ctx, req8, user_sid, &r->out.ctr->ctr6);
1314                         r->out.result = werr;
1315                         W_ERROR_NOT_OK_RETURN(werr);
1316                         break;
1317                 case DRSUAPI_EXOP_FSMO_REQ_ROLE:
1318                         werr = getncchanges_change_master(b_state, mem_ctx, req8, &r->out.ctr->ctr6);
1319                         W_ERROR_NOT_OK_RETURN(werr);
1320                         break;
1321                 case DRSUAPI_EXOP_FSMO_RID_REQ_ROLE:
1322                         werr = getncchanges_change_master(b_state, mem_ctx, req8, &r->out.ctr->ctr6);
1323                         W_ERROR_NOT_OK_RETURN(werr);
1324                         break;
1325                 case DRSUAPI_EXOP_FSMO_REQ_PDC:
1326                         werr = getncchanges_change_master(b_state, mem_ctx, req8, &r->out.ctr->ctr6);
1327                         W_ERROR_NOT_OK_RETURN(werr);
1328                         break;
1329                 case DRSUAPI_EXOP_REPL_OBJ:
1330                         werr = getncchanges_repl_obj(b_state, mem_ctx, req8, user_sid, &r->out.ctr->ctr6);
1331                         r->out.result = werr;
1332                         W_ERROR_NOT_OK_RETURN(werr);
1333                         break;
1334
1335                 case DRSUAPI_EXOP_FSMO_ABANDON_ROLE:
1336
1337                         DEBUG(0,(__location__ ": Request for DsGetNCChanges unsupported extended op 0x%x\n",
1338                                  (unsigned)req8->extended_op));
1339                         return WERR_DS_DRA_NOT_SUPPORTED;
1340                 }
1341         }
1342
1343         if (!ldb_dn_validate(getnc_state->ncRoot_dn) ||
1344             ldb_dn_is_null(getnc_state->ncRoot_dn)) {
1345                 DEBUG(0,(__location__ ": Bad DN '%s'\n",
1346                          drs_ObjectIdentifier_to_string(mem_ctx, ncRoot)));
1347                 return WERR_DS_DRA_INVALID_PARAMETER;
1348         }
1349
1350         /* we need the session key for encrypting password attributes */
1351         status = dcesrv_inherited_session_key(dce_call->conn, &session_key);
1352         if (!NT_STATUS_IS_OK(status)) {
1353                 DEBUG(0,(__location__ ": Failed to get session key\n"));
1354                 return WERR_DS_DRA_INTERNAL_ERROR;              
1355         }
1356
1357         /* 
1358            TODO: MS-DRSR section 4.1.10.1.1
1359            Work out if this is the start of a new cycle */
1360
1361         if (getnc_state->site_res == NULL) {
1362                 char* search_filter;
1363                 enum ldb_scope scope = LDB_SCOPE_SUBTREE;
1364                 const char *extra_filter;
1365
1366                 if (req8->extended_op == DRSUAPI_EXOP_REPL_OBJ ||
1367                     req8->extended_op == DRSUAPI_EXOP_REPL_SECRET) {
1368                         scope = LDB_SCOPE_BASE;
1369                 }
1370
1371                 extra_filter = lpcfg_parm_string(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "object filter");
1372
1373                 getnc_state->min_usn = req8->highwatermark.highest_usn;
1374
1375                 /* Construct response. */
1376                 search_filter = talloc_asprintf(mem_ctx,
1377                                                 "(uSNChanged>=%llu)",
1378                                                 (unsigned long long)(getnc_state->min_usn+1));
1379         
1380                 if (extra_filter) {
1381                         search_filter = talloc_asprintf(mem_ctx, "(&%s(%s))", search_filter, extra_filter);
1382                 }
1383
1384                 if (req8->replica_flags & DRSUAPI_DRS_CRITICAL_ONLY) {
1385                         search_filter = talloc_asprintf(mem_ctx,
1386                                                         "(&%s(isCriticalSystemObject=TRUE))",
1387                                                         search_filter);
1388                 }
1389                 
1390                 if (req8->replica_flags & DRSUAPI_DRS_ASYNC_REP) {
1391                         scope = LDB_SCOPE_BASE;
1392                 }
1393                 
1394                 if (!search_dn) {
1395                         search_dn = getnc_state->ncRoot_dn;
1396                 }
1397
1398                 DEBUG(2,(__location__ ": getncchanges on %s using filter %s\n",
1399                          ldb_dn_get_linearized(getnc_state->ncRoot_dn), search_filter));
1400                 ret = drsuapi_search_with_extended_dn(sam_ctx, getnc_state, &getnc_state->site_res,
1401                                                       search_dn, scope, attrs,
1402                                                       search_filter);
1403                 if (ret != LDB_SUCCESS) {
1404                         return WERR_DS_DRA_INTERNAL_ERROR;
1405                 }
1406
1407                 if (req8->replica_flags & DRSUAPI_DRS_GET_ANC) {
1408                         TYPESAFE_QSORT(getnc_state->site_res->msgs,
1409                                        getnc_state->site_res->count,
1410                                        site_res_cmp_parent_order);
1411                 } else {
1412                         TYPESAFE_QSORT(getnc_state->site_res->msgs,
1413                                        getnc_state->site_res->count,
1414                                        site_res_cmp_usn_order);
1415                 }
1416
1417                 getnc_state->uptodateness_vector = talloc_steal(getnc_state, req8->uptodateness_vector);
1418                 if (getnc_state->uptodateness_vector) {
1419                         /* make sure its sorted */
1420                         TYPESAFE_QSORT(getnc_state->uptodateness_vector->cursors,
1421                                        getnc_state->uptodateness_vector->count,
1422                                        drsuapi_DsReplicaCursor_compare);
1423                 }
1424         }
1425
1426         /* Prefix mapping */
1427         schema = dsdb_get_schema(sam_ctx, mem_ctx);
1428         if (!schema) {
1429                 DEBUG(0,("No schema in sam_ctx\n"));
1430                 return WERR_DS_DRA_INTERNAL_ERROR;
1431         }
1432
1433         r->out.ctr->ctr6.naming_context = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
1434         *r->out.ctr->ctr6.naming_context = *ncRoot;
1435
1436         if (dsdb_find_guid_by_dn(sam_ctx, getnc_state->ncRoot_dn,
1437                                  &r->out.ctr->ctr6.naming_context->guid) != LDB_SUCCESS) {
1438                 DEBUG(0,(__location__ ": Failed to find GUID of ncRoot_dn %s\n",
1439                          ldb_dn_get_linearized(getnc_state->ncRoot_dn)));
1440                 return WERR_DS_DRA_INTERNAL_ERROR;
1441         }
1442
1443         /* find the SID if there is one */
1444         dsdb_find_sid_by_dn(sam_ctx, getnc_state->ncRoot_dn, &r->out.ctr->ctr6.naming_context->sid);
1445
1446         dsdb_get_oid_mappings_drsuapi(schema, true, mem_ctx, &ctr);
1447         r->out.ctr->ctr6.mapping_ctr = *ctr;
1448
1449         r->out.ctr->ctr6.source_dsa_guid = *(samdb_ntds_objectGUID(sam_ctx));
1450         r->out.ctr->ctr6.source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
1451
1452         r->out.ctr->ctr6.old_highwatermark = req8->highwatermark;
1453         r->out.ctr->ctr6.new_highwatermark = req8->highwatermark;
1454
1455         r->out.ctr->ctr6.first_object = NULL;
1456         currentObject = &r->out.ctr->ctr6.first_object;
1457
1458         /* use this to force single objects at a time, which is useful
1459          * for working out what object is giving problems
1460          */
1461         max_objects = lpcfg_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max object sync", 1000);
1462         if (req8->max_object_count < max_objects) {
1463                 max_objects = req8->max_object_count;
1464         }
1465         /*
1466          * TODO: work out how the maximum should be calculated
1467          */
1468         max_links = lpcfg_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max link sync", 1500);
1469
1470         for (i=getnc_state->num_sent;
1471              i<getnc_state->site_res->count &&
1472                      !null_scope &&
1473                      (r->out.ctr->ctr6.object_count < max_objects);
1474             i++) {
1475                 int uSN;
1476                 struct drsuapi_DsReplicaObjectListItemEx *obj;
1477                 struct ldb_message *msg = getnc_state->site_res->msgs[i];
1478
1479                 obj = talloc_zero(mem_ctx, struct drsuapi_DsReplicaObjectListItemEx);
1480
1481                 werr = get_nc_changes_build_object(obj, msg,
1482                                                    sam_ctx, getnc_state->ncRoot_dn,
1483                                                    getnc_state->is_schema_nc,
1484                                                    schema, &session_key, getnc_state->min_usn,
1485                                                    req8->replica_flags,
1486                                                    req8->partial_attribute_set,
1487                                                    getnc_state->uptodateness_vector,
1488                                                    req8->extended_op);
1489                 if (!W_ERROR_IS_OK(werr)) {
1490                         return werr;
1491                 }
1492
1493                 werr = get_nc_changes_add_links(sam_ctx, getnc_state,
1494                                                 getnc_state->ncRoot_dn,
1495                                                 schema, getnc_state->min_usn,
1496                                                 req8->replica_flags,
1497                                                 msg,
1498                                                 &getnc_state->la_list,
1499                                                 &getnc_state->la_count,
1500                                                 getnc_state->uptodateness_vector);
1501                 if (!W_ERROR_IS_OK(werr)) {
1502                         return werr;
1503                 }
1504
1505                 uSN = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
1506                 if (uSN > r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn) {
1507                         r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn = uSN;
1508                 }
1509                 if (uSN > getnc_state->highest_usn) {
1510                         getnc_state->highest_usn = uSN;
1511                 }
1512
1513                 if (obj->meta_data_ctr == NULL) {
1514                         DEBUG(8,(__location__ ": getncchanges skipping send of object %s\n",
1515                                  ldb_dn_get_linearized(msg->dn)));
1516                         /* no attributes to send */
1517                         talloc_free(obj);
1518                         continue;
1519                 }
1520
1521                 r->out.ctr->ctr6.object_count++;
1522                 
1523                 *currentObject = obj;
1524                 currentObject = &obj->next_object;
1525
1526                 talloc_free(getnc_state->last_dn);
1527                 getnc_state->last_dn = ldb_dn_copy(getnc_state, msg->dn);
1528
1529                 DEBUG(8,(__location__ ": replicating object %s\n", ldb_dn_get_linearized(msg->dn)));
1530         }
1531
1532         getnc_state->num_sent += r->out.ctr->ctr6.object_count;
1533
1534         r->out.ctr->ctr6.nc_object_count = getnc_state->site_res->count;
1535
1536         /* the client can us to call UpdateRefs on its behalf to
1537            re-establish monitoring of the NC */
1538         if ((req8->replica_flags & (DRSUAPI_DRS_ADD_REF | DRSUAPI_DRS_REF_GCSPN)) &&
1539             !GUID_all_zero(&req8->destination_dsa_guid)) {
1540                 struct drsuapi_DsReplicaUpdateRefsRequest1 ureq;
1541                 DEBUG(3,("UpdateRefs on getncchanges for %s\n",
1542                          GUID_string(mem_ctx, &req8->destination_dsa_guid)));
1543                 ureq.naming_context = ncRoot;
1544                 ureq.dest_dsa_dns_name = talloc_asprintf(mem_ctx, "%s._msdcs.%s",
1545                                                          GUID_string(mem_ctx, &req8->destination_dsa_guid),
1546                                                          lpcfg_dnsdomain(dce_call->conn->dce_ctx->lp_ctx));
1547                 if (!ureq.dest_dsa_dns_name) {
1548                         return WERR_NOMEM;
1549                 }
1550                 ureq.dest_dsa_guid = req8->destination_dsa_guid;
1551                 ureq.options = DRSUAPI_DRS_ADD_REF |
1552                         DRSUAPI_DRS_ASYNC_OP |
1553                         DRSUAPI_DRS_GETCHG_CHECK;
1554                 werr = drsuapi_UpdateRefs(b_state, mem_ctx, &ureq);
1555                 if (!W_ERROR_IS_OK(werr)) {
1556                         DEBUG(0,(__location__ ": Failed UpdateRefs in DsGetNCChanges - %s\n",
1557                                  win_errstr(werr)));
1558                 }
1559         }
1560
1561         /*
1562          * TODO:
1563          * This is just a guess, how to calculate the
1564          * number of linked attributes to send, we need to
1565          * find out how to do this right.
1566          */
1567         if (r->out.ctr->ctr6.object_count >= max_links) {
1568                 max_links = 0;
1569         } else {
1570                 max_links -= r->out.ctr->ctr6.object_count;
1571         }
1572
1573         link_total = getnc_state->la_count;
1574
1575         if (i < getnc_state->site_res->count) {
1576                 r->out.ctr->ctr6.more_data = true;
1577         } else {
1578                 /* sort the whole array the first time */
1579                 if (!getnc_state->la_sorted) {
1580                         LDB_TYPESAFE_QSORT(getnc_state->la_list, getnc_state->la_count,
1581                                            sam_ctx, linked_attribute_compare);
1582                         getnc_state->la_sorted = true;
1583                 }
1584
1585                 link_count = getnc_state->la_count - getnc_state->la_idx;
1586                 link_count = MIN(max_links, link_count);
1587
1588                 r->out.ctr->ctr6.linked_attributes_count = link_count;
1589                 r->out.ctr->ctr6.linked_attributes = getnc_state->la_list + getnc_state->la_idx;
1590
1591                 getnc_state->la_idx += link_count;
1592                 link_given = getnc_state->la_idx;
1593
1594                 if (getnc_state->la_idx < getnc_state->la_count) {
1595                         r->out.ctr->ctr6.more_data = true;
1596                 }
1597         }
1598
1599         if (!r->out.ctr->ctr6.more_data) {
1600                 talloc_steal(mem_ctx, getnc_state->la_list);
1601
1602                 r->out.ctr->ctr6.uptodateness_vector = talloc(mem_ctx, struct drsuapi_DsReplicaCursor2CtrEx);
1603                 r->out.ctr->ctr6.new_highwatermark.highest_usn = r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn;
1604
1605                 werr = get_nc_changes_udv(sam_ctx, getnc_state->ncRoot_dn,
1606                                           r->out.ctr->ctr6.uptodateness_vector);
1607                 if (!W_ERROR_IS_OK(werr)) {
1608                         return werr;
1609                 }
1610
1611                 talloc_free(getnc_state);
1612                 b_state->getncchanges_state = NULL;
1613         }
1614
1615         if (req8->extended_op != DRSUAPI_EXOP_NONE) {
1616                 r->out.ctr->ctr6.uptodateness_vector = NULL;
1617                 r->out.ctr->ctr6.nc_object_count = 0;
1618                 ZERO_STRUCT(r->out.ctr->ctr6.new_highwatermark);
1619                 r->out.ctr->ctr6.extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
1620         }
1621
1622         DEBUG(r->out.ctr->ctr6.more_data?4:2,
1623               ("DsGetNCChanges with uSNChanged >= %llu flags 0x%08x on %s gave %u objects (done %u/%u) %u links (done %u/%u (as %s))\n",
1624                (unsigned long long)(req8->highwatermark.highest_usn+1),
1625                req8->replica_flags, drs_ObjectIdentifier_to_string(mem_ctx, ncRoot),
1626                r->out.ctr->ctr6.object_count,
1627                i, r->out.ctr->ctr6.more_data?getnc_state->site_res->count:i,
1628                r->out.ctr->ctr6.linked_attributes_count,
1629                link_given, link_total,
1630                dom_sid_string(mem_ctx, user_sid)));
1631
1632 #if 0
1633         if (!r->out.ctr->ctr6.more_data && req8->extended_op != DRSUAPI_EXOP_NONE) {
1634                 NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsGetNCChanges, NDR_BOTH, r);
1635         }
1636 #endif
1637
1638         return WERR_OK;
1639 }