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