dc50fc0c0ca5841f7ce7c731b8552908ac5e94d6
[kai/samba.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 "libcli/security/security.h"
31 #include "libcli/security/session.h"
32 #include "rpc_server/drsuapi/dcesrv_drsuapi.h"
33 #include "rpc_server/dcerpc_server_proto.h"
34 #include "../libcli/drsuapi/drsuapi.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_ATTID_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_ATTID_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_ATTID_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         if (!active) {
361                 /* We have to check that the inactive link still point to an existing object */
362                 struct GUID guid;
363                 struct ldb_dn *tdn;
364                 int ret;
365
366                 status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &guid, "GUID");
367                 if (!NT_STATUS_IS_OK(status)) {
368                         DEBUG(0,(__location__ " Unable to extract GUID in linked attribute '%s' in '%s'\n",
369                                 sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
370                         return ntstatus_to_werror(status);
371                 }
372                 ret = dsdb_find_dn_by_guid(sam_ctx, mem_ctx, &guid, &tdn);
373                 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
374                         DEBUG(2, (" Search of guid %s returned 0 objects, skipping it !\n",
375                                                 GUID_string(mem_ctx, &guid)));
376                         return WERR_OK;
377                 } else if (ret != LDB_SUCCESS) {
378                         DEBUG(0, (__location__ " Search of guid %s failed with error code %d\n",
379                                                 GUID_string(mem_ctx, &guid),
380                                                 ret));
381                         return WERR_OK;
382                 }
383         }
384         la->attid = sa->attributeID_id;
385         la->flags = active?DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE:0;
386
387         status = dsdb_get_extended_dn_uint32(dsdb_dn->dn, &la->meta_data.version, "RMD_VERSION");
388         if (!NT_STATUS_IS_OK(status)) {
389                 DEBUG(0,(__location__ " No RMD_VERSION in linked attribute '%s' in '%s'\n",
390                          sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
391                 return ntstatus_to_werror(status);
392         }
393         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->meta_data.originating_change_time, "RMD_CHANGETIME");
394         if (!NT_STATUS_IS_OK(status)) {
395                 DEBUG(0,(__location__ " No RMD_CHANGETIME in linked attribute '%s' in '%s'\n",
396                          sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
397                 return ntstatus_to_werror(status);
398         }
399         status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &la->meta_data.originating_invocation_id, "RMD_INVOCID");
400         if (!NT_STATUS_IS_OK(status)) {
401                 DEBUG(0,(__location__ " No RMD_INVOCID in linked attribute '%s' in '%s'\n",
402                          sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
403                 return ntstatus_to_werror(status);
404         }
405         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &la->meta_data.originating_usn, "RMD_ORIGINATING_USN");
406         if (!NT_STATUS_IS_OK(status)) {
407                 DEBUG(0,(__location__ " No RMD_ORIGINATING_USN in linked attribute '%s' in '%s'\n",
408                          sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
409                 return ntstatus_to_werror(status);
410         }
411
412         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->originating_add_time, "RMD_ADDTIME");
413         if (!NT_STATUS_IS_OK(status)) {
414                 /* this is possible for upgraded links */
415                 la->originating_add_time = la->meta_data.originating_change_time;
416         }
417
418         werr = dsdb_dn_la_to_blob(sam_ctx, sa, schema, *la_list, dsdb_dn, &la->value.blob);
419         W_ERROR_NOT_OK_RETURN(werr);
420
421         (*la_count)++;
422         return WERR_OK;
423 }
424
425
426 /*
427   add linked attributes from an object to the list of linked
428   attributes in a getncchanges request
429  */
430 static WERROR get_nc_changes_add_links(struct ldb_context *sam_ctx,
431                                        TALLOC_CTX *mem_ctx,
432                                        struct ldb_dn *ncRoot_dn,
433                                        struct dsdb_schema *schema,
434                                        uint64_t highest_usn,
435                                        uint32_t replica_flags,
436                                        struct ldb_message *msg,
437                                        struct drsuapi_DsReplicaLinkedAttribute **la_list,
438                                        uint32_t *la_count,
439                                        struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector)
440 {
441         unsigned int i;
442         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
443         uint64_t uSNChanged = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
444
445         for (i=0; i<msg->num_elements; i++) {
446                 struct ldb_message_element *el = &msg->elements[i];
447                 const struct dsdb_attribute *sa;
448                 unsigned int j;
449
450                 sa = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
451
452                 if (!sa || sa->linkID == 0 || (sa->linkID & 1)) {
453                         /* we only want forward links */
454                         continue;
455                 }
456
457                 if (el->num_values && !dsdb_dn_is_upgraded_link_val(&el->values[0])) {
458                         /* its an old style link, it will have been
459                          * sent in the main replication data */
460                         continue;
461                 }
462
463                 for (j=0; j<el->num_values; j++) {
464                         struct dsdb_dn *dsdb_dn;
465                         uint64_t local_usn;
466                         NTSTATUS status;
467                         WERROR werr;
468
469                         dsdb_dn = dsdb_dn_parse(tmp_ctx, sam_ctx, &el->values[j], sa->syntax->ldap_oid);
470                         if (dsdb_dn == NULL) {
471                                 DEBUG(1,(__location__ ": Failed to parse DN for %s in %s\n",
472                                          el->name, ldb_dn_get_linearized(msg->dn)));
473                                 talloc_free(tmp_ctx);
474                                 return WERR_DS_DRA_INTERNAL_ERROR;
475                         }
476
477                         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &local_usn, "RMD_LOCAL_USN");
478                         if (!NT_STATUS_IS_OK(status)) {
479                                 /* this can happen for attributes
480                                    given to us with old style meta
481                                    data */
482                                 continue;
483                         }
484
485                         if (local_usn > uSNChanged) {
486                                 DEBUG(1,(__location__ ": uSNChanged less than RMD_LOCAL_USN for %s on %s\n",
487                                          el->name, ldb_dn_get_linearized(msg->dn)));
488                                 talloc_free(tmp_ctx);
489                                 return WERR_DS_DRA_INTERNAL_ERROR;
490                         }
491
492                         if (local_usn < highest_usn) {
493                                 continue;
494                         }
495
496                         werr = get_nc_changes_add_la(mem_ctx, sam_ctx, schema, sa, msg,
497                                                      dsdb_dn, la_list, la_count);
498                         if (!W_ERROR_IS_OK(werr)) {
499                                 talloc_free(tmp_ctx);
500                                 return werr;
501                         }
502                 }
503         }
504
505         talloc_free(tmp_ctx);
506         return WERR_OK;
507 }
508
509 /*
510   fill in the cursors return based on the replUpToDateVector for the ncRoot_dn
511  */
512 static WERROR get_nc_changes_udv(struct ldb_context *sam_ctx,
513                                  struct ldb_dn *ncRoot_dn,
514                                  struct drsuapi_DsReplicaCursor2CtrEx *udv)
515 {
516         int ret;
517
518         udv->version = 2;
519         udv->reserved1 = 0;
520         udv->reserved2 = 0;
521
522         ret = dsdb_load_udv_v2(sam_ctx, ncRoot_dn, udv, &udv->cursors, &udv->count);
523         if (ret != LDB_SUCCESS) {
524                 DEBUG(0,(__location__ ": Failed to load UDV for %s - %s\n",
525                          ldb_dn_get_linearized(ncRoot_dn), ldb_errstring(sam_ctx)));
526                 return WERR_DS_DRA_INTERNAL_ERROR;
527         }
528         
529         return WERR_OK;
530 }
531
532
533 /* comparison function for linked attributes - see CompareLinks() in
534  * MS-DRSR section 4.1.10.5.17 */
535 static int linked_attribute_compare(const struct drsuapi_DsReplicaLinkedAttribute *la1,
536                                     const struct drsuapi_DsReplicaLinkedAttribute *la2,
537                                     struct ldb_context *sam_ctx)
538 {
539         int c;
540         WERROR werr;
541         TALLOC_CTX *tmp_ctx;
542         const struct dsdb_schema *schema;
543         const struct dsdb_attribute *schema_attrib;
544         struct dsdb_dn *dn1, *dn2;
545         struct GUID guid1, guid2;
546         NTSTATUS status;
547
548         c = GUID_compare(&la1->identifier->guid,
549                          &la2->identifier->guid);
550         if (c != 0) return c;
551
552         if (la1->attid != la2->attid) {
553                 return la1->attid < la2->attid? -1:1;
554         }
555
556         if ((la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE) !=
557             (la2->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)) {
558                 return (la1->flags & DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE)? 1:-1;
559         }
560
561         /* we need to get the target GUIDs to compare */
562         tmp_ctx = talloc_new(sam_ctx);
563
564         schema = dsdb_get_schema(sam_ctx, tmp_ctx);
565         schema_attrib = dsdb_attribute_by_attributeID_id(schema, la1->attid);
566
567         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la1->value.blob, &dn1);
568         if (!W_ERROR_IS_OK(werr)) {
569                 DEBUG(0,(__location__ ": Bad la1 blob in sort\n"));
570                 talloc_free(tmp_ctx);
571                 return 0;
572         }
573
574         werr = dsdb_dn_la_from_blob(sam_ctx, schema_attrib, schema, tmp_ctx, la2->value.blob, &dn2);
575         if (!W_ERROR_IS_OK(werr)) {
576                 DEBUG(0,(__location__ ": Bad la2 blob in sort\n"));
577                 talloc_free(tmp_ctx);
578                 return 0;
579         }
580
581         status = dsdb_get_extended_dn_guid(dn1->dn, &guid1, "GUID");
582         if (!NT_STATUS_IS_OK(status)) {
583                 DEBUG(0,(__location__ ": Bad la1 guid in sort\n"));
584                 talloc_free(tmp_ctx);
585                 return 0;
586         }
587         status = dsdb_get_extended_dn_guid(dn2->dn, &guid2, "GUID");
588         if (!NT_STATUS_IS_OK(status)) {
589                 DEBUG(0,(__location__ ": Bad la2 guid in sort\n"));
590                 talloc_free(tmp_ctx);
591                 return 0;
592         }
593
594         talloc_free(tmp_ctx);
595
596         return GUID_compare(&guid1, &guid2);
597 }
598
599
600 /*
601   sort the objects we send by tree order
602  */
603 static int site_res_cmp_parent_order(struct ldb_message **m1, struct ldb_message **m2)
604 {
605         return ldb_dn_compare((*m2)->dn, (*m1)->dn);
606 }
607
608 /*
609   sort the objects we send first by uSNChanged
610  */
611 static int site_res_cmp_usn_order(struct ldb_message **m1, struct ldb_message **m2)
612 {
613         unsigned usnchanged1, usnchanged2;
614         unsigned cn1, cn2;
615         cn1 = ldb_dn_get_comp_num((*m1)->dn);
616         cn2 = ldb_dn_get_comp_num((*m2)->dn);
617         if (cn1 != cn2) {
618                 return cn1 > cn2 ? 1 : -1;
619         }
620         usnchanged1 = ldb_msg_find_attr_as_uint(*m1, "uSNChanged", 0);
621         usnchanged2 = ldb_msg_find_attr_as_uint(*m2, "uSNChanged", 0);
622         if (usnchanged1 == usnchanged2) {
623                 return 0;
624         }
625         return usnchanged1 > usnchanged2 ? 1 : -1;
626 }
627
628
629 /*
630   handle a DRSUAPI_EXOP_FSMO_RID_ALLOC call
631  */
632 static WERROR getncchanges_rid_alloc(struct drsuapi_bind_state *b_state,
633                                      TALLOC_CTX *mem_ctx,
634                                      struct drsuapi_DsGetNCChangesRequest10 *req10,
635                                      struct drsuapi_DsGetNCChangesCtr6 *ctr6)
636 {
637         struct ldb_dn *rid_manager_dn, *fsmo_role_dn, *req_dn;
638         int ret;
639         struct ldb_context *ldb = b_state->sam_ctx;
640         struct ldb_result *ext_res;
641         struct ldb_dn *base_dn;
642         struct dsdb_fsmo_extended_op *exop;
643
644         /*
645           steps:
646             - verify that the DN being asked for is the RID Manager DN
647             - verify that we are the RID Manager
648          */
649
650         /* work out who is the RID Manager */
651         ret = samdb_rid_manager_dn(ldb, mem_ctx, &rid_manager_dn);
652         if (ret != LDB_SUCCESS) {
653                 DEBUG(0, (__location__ ": Failed to find RID Manager object - %s\n", ldb_errstring(ldb)));
654                 return WERR_DS_DRA_INTERNAL_ERROR;
655         }
656
657         req_dn = drs_ObjectIdentifier_to_dn(mem_ctx, ldb, req10->naming_context);
658         if (!ldb_dn_validate(req_dn) ||
659             ldb_dn_compare(req_dn, rid_manager_dn) != 0) {
660                 /* that isn't the RID Manager DN */
661                 DEBUG(0,(__location__ ": RID Alloc request for wrong DN %s\n",
662                          drs_ObjectIdentifier_to_string(mem_ctx, req10->naming_context)));
663                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_MISMATCH;
664                 return WERR_OK;
665         }
666
667         /* find the DN of the RID Manager */
668         ret = samdb_reference_dn(ldb, mem_ctx, rid_manager_dn, "fSMORoleOwner", &fsmo_role_dn);
669         if (ret != LDB_SUCCESS) {
670                 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s\n",
671                          ldb_errstring(ldb)));
672                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
673                 return WERR_DS_DRA_INTERNAL_ERROR;
674         }
675
676         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), fsmo_role_dn) != 0) {
677                 /* we're not the RID Manager - go away */
678                 DEBUG(0,(__location__ ": RID Alloc request when not RID Manager\n"));
679                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
680                 return WERR_OK;
681         }
682
683         exop = talloc(mem_ctx, struct dsdb_fsmo_extended_op);
684         W_ERROR_HAVE_NO_MEMORY(exop);
685
686         exop->fsmo_info = req10->fsmo_info;
687         exop->destination_dsa_guid = req10->destination_dsa_guid;
688
689         ret = ldb_transaction_start(ldb);
690         if (ret != LDB_SUCCESS) {
691                 DEBUG(0,(__location__ ": Failed transaction start - %s\n",
692                          ldb_errstring(ldb)));
693                 return WERR_DS_DRA_INTERNAL_ERROR;
694         }
695
696         /*
697          * FIXME (kim): this is a temp hack to return just few object,
698          * but not the whole domain NC.
699          * We should remove this hack and implement a 'scope'
700          * building function to return just the set of object
701          * documented for DRSUAPI_EXOP_FSMO_RID_ALLOC extended_op
702          */
703         ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &req10->highwatermark.highest_usn);
704
705         ret = ldb_extended(ldb, DSDB_EXTENDED_ALLOCATE_RID_POOL, exop, &ext_res);
706         if (ret != LDB_SUCCESS) {
707                 DEBUG(0,(__location__ ": Failed extended allocation RID pool operation - %s\n",
708                          ldb_errstring(ldb)));
709                 ldb_transaction_cancel(ldb);
710                 return WERR_DS_DRA_INTERNAL_ERROR;
711         }
712
713         ret = ldb_transaction_commit(ldb);
714         if (ret != LDB_SUCCESS) {
715                 DEBUG(0,(__location__ ": Failed transaction commit - %s\n",
716                          ldb_errstring(ldb)));
717                 return WERR_DS_DRA_INTERNAL_ERROR;
718         }
719
720         talloc_free(ext_res);
721
722         base_dn = ldb_get_default_basedn(ldb);
723
724         DEBUG(2,("Allocated RID pool for server %s\n",
725                  GUID_string(mem_ctx, &req10->destination_dsa_guid)));
726
727         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
728
729         return WERR_OK;
730 }
731
732 /*
733   return an array of SIDs from a ldb_message given an attribute name
734   assumes the SIDs are in extended DN format
735  */
736 static WERROR samdb_result_sid_array_dn(struct ldb_context *sam_ctx,
737                                         struct ldb_message *msg,
738                                         TALLOC_CTX *mem_ctx,
739                                         const char *attr,
740                                         const struct dom_sid ***sids)
741 {
742         struct ldb_message_element *el;
743         unsigned int i;
744
745         el = ldb_msg_find_element(msg, attr);
746         if (!el) {
747                 *sids = NULL;
748                 return WERR_OK;
749         }
750
751         (*sids) = talloc_array(mem_ctx, const struct dom_sid *, el->num_values + 1);
752         W_ERROR_HAVE_NO_MEMORY(*sids);
753
754         for (i=0; i<el->num_values; i++) {
755                 struct ldb_dn *dn = ldb_dn_from_ldb_val(mem_ctx, sam_ctx, &el->values[i]);
756                 NTSTATUS status;
757                 struct dom_sid *sid;
758
759                 sid = talloc(*sids, struct dom_sid);
760                 W_ERROR_HAVE_NO_MEMORY(sid);
761                 status = dsdb_get_extended_dn_sid(dn, sid, "SID");
762                 if (!NT_STATUS_IS_OK(status)) {
763                         return WERR_INTERNAL_DB_CORRUPTION;
764                 }
765                 (*sids)[i] = sid;
766         }
767         (*sids)[i] = NULL;
768
769         return WERR_OK;
770 }
771
772
773 /*
774   return an array of SIDs from a ldb_message given an attribute name
775   assumes the SIDs are in NDR form
776  */
777 static WERROR samdb_result_sid_array_ndr(struct ldb_context *sam_ctx,
778                                          struct ldb_message *msg,
779                                          TALLOC_CTX *mem_ctx,
780                                          const char *attr,
781                                          const struct dom_sid ***sids)
782 {
783         struct ldb_message_element *el;
784         unsigned int i;
785
786         el = ldb_msg_find_element(msg, attr);
787         if (!el) {
788                 *sids = NULL;
789                 return WERR_OK;
790         }
791
792         (*sids) = talloc_array(mem_ctx, const struct dom_sid *, el->num_values + 1);
793         W_ERROR_HAVE_NO_MEMORY(*sids);
794
795         for (i=0; i<el->num_values; i++) {
796                 enum ndr_err_code ndr_err;
797                 struct dom_sid *sid;
798
799                 sid = talloc(*sids, struct dom_sid);
800                 W_ERROR_HAVE_NO_MEMORY(sid);
801
802                 ndr_err = ndr_pull_struct_blob(&el->values[i], sid, sid,
803                                                (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
804                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
805                         return WERR_INTERNAL_DB_CORRUPTION;
806                 }
807                 (*sids)[i] = sid;
808         }
809         (*sids)[i] = NULL;
810
811         return WERR_OK;
812 }
813
814 /*
815   see if any SIDs in list1 are in list2
816  */
817 static bool sid_list_match(const struct dom_sid **list1, const struct dom_sid **list2)
818 {
819         unsigned int i, j;
820         /* do we ever have enough SIDs here to worry about O(n^2) ? */
821         for (i=0; list1[i]; i++) {
822                 for (j=0; list2[j]; j++) {
823                         if (dom_sid_equal(list1[i], list2[j])) {
824                                 return true;
825                         }
826                 }
827         }
828         return false;
829 }
830
831 /*
832   handle a DRSUAPI_EXOP_REPL_SECRET call
833  */
834 static WERROR getncchanges_repl_secret(struct drsuapi_bind_state *b_state,
835                                        TALLOC_CTX *mem_ctx,
836                                        struct drsuapi_DsGetNCChangesRequest10 *req10,
837                                        struct dom_sid *user_sid,
838                                        struct drsuapi_DsGetNCChangesCtr6 *ctr6)
839 {
840         struct drsuapi_DsReplicaObjectIdentifier *ncRoot = req10->naming_context;
841         struct ldb_dn *obj_dn, *rodc_dn, *krbtgt_link_dn;
842         int ret;
843         const char *rodc_attrs[] = { "msDS-KrbTgtLink", "msDS-NeverRevealGroup", "msDS-RevealOnDemandGroup", NULL };
844         const char *obj_attrs[] = { "tokenGroups", "objectSid", "UserAccountControl", "msDS-KrbTgtLinkBL", NULL };
845         struct ldb_result *rodc_res, *obj_res;
846         const struct dom_sid **never_reveal_sids, **reveal_sids, **token_sids;
847         WERROR werr;
848
849         DEBUG(3,(__location__ ": DRSUAPI_EXOP_REPL_SECRET extended op on %s\n",
850                  drs_ObjectIdentifier_to_string(mem_ctx, ncRoot)));
851
852         /*
853          * we need to work out if we will allow this RODC to
854          * replicate the secrets for this object
855          *
856          * see 4.1.10.5.14 GetRevealSecretsPolicyForUser for details
857          * of this function
858          */
859
860         if (b_state->sam_ctx_system == NULL) {
861                 /* this operation needs system level access */
862                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_ACCESS_DENIED;
863                 return WERR_DS_DRA_SOURCE_DISABLED;
864         }
865
866         obj_dn = drs_ObjectIdentifier_to_dn(mem_ctx, b_state->sam_ctx_system, ncRoot);
867         if (!ldb_dn_validate(obj_dn)) goto failed;
868
869         rodc_dn = ldb_dn_new_fmt(mem_ctx, b_state->sam_ctx_system, "<SID=%s>",
870                                  dom_sid_string(mem_ctx, user_sid));
871         if (!ldb_dn_validate(rodc_dn)) goto failed;
872
873         /* do the two searches we need */
874         ret = dsdb_search_dn(b_state->sam_ctx_system, mem_ctx, &rodc_res, rodc_dn, rodc_attrs,
875                              DSDB_SEARCH_SHOW_EXTENDED_DN);
876         if (ret != LDB_SUCCESS || rodc_res->count != 1) goto failed;
877
878         ret = dsdb_search_dn(b_state->sam_ctx_system, mem_ctx, &obj_res, obj_dn, obj_attrs, 0);
879         if (ret != LDB_SUCCESS || obj_res->count != 1) goto failed;
880
881         /* if the object SID is equal to the user_sid, allow */
882         if (dom_sid_equal(user_sid,
883                           samdb_result_dom_sid(mem_ctx, obj_res->msgs[0], "objectSid"))) {
884                 goto allowed;
885         }
886
887         /* an RODC is allowed to get its own krbtgt account secrets */
888         krbtgt_link_dn = samdb_result_dn(b_state->sam_ctx_system, mem_ctx,
889                                          rodc_res->msgs[0], "msDS-KrbTgtLink", NULL);
890         if (krbtgt_link_dn != NULL &&
891             ldb_dn_compare(obj_dn, krbtgt_link_dn) == 0) {
892                 goto allowed;
893         }
894
895         /* but it isn't allowed to get anyone elses krbtgt secrets */
896         if (samdb_result_dn(b_state->sam_ctx_system, mem_ctx,
897                             obj_res->msgs[0], "msDS-KrbTgtLinkBL", NULL)) {
898                 goto denied;
899         }
900
901         if (ldb_msg_find_attr_as_uint(obj_res->msgs[0],
902                                       "userAccountControl", 0) &
903             UF_INTERDOMAIN_TRUST_ACCOUNT) {
904                 goto denied;
905         }
906
907         werr = samdb_result_sid_array_dn(b_state->sam_ctx_system, rodc_res->msgs[0],
908                                          mem_ctx, "msDS-NeverRevealGroup", &never_reveal_sids);
909         if (!W_ERROR_IS_OK(werr)) {
910                 goto denied;
911         }
912
913         werr = samdb_result_sid_array_dn(b_state->sam_ctx_system, rodc_res->msgs[0],
914                                          mem_ctx, "msDS-RevealOnDemandGroup", &reveal_sids);
915         if (!W_ERROR_IS_OK(werr)) {
916                 goto denied;
917         }
918
919         werr = samdb_result_sid_array_ndr(b_state->sam_ctx_system, obj_res->msgs[0],
920                                          mem_ctx, "tokenGroups", &token_sids);
921         if (!W_ERROR_IS_OK(werr) || token_sids==NULL) {
922                 goto denied;
923         }
924
925         if (never_reveal_sids &&
926             sid_list_match(token_sids, never_reveal_sids)) {
927                 goto denied;
928         }
929
930         if (reveal_sids &&
931             sid_list_match(token_sids, reveal_sids)) {
932                 goto allowed;
933         }
934
935         /* default deny */
936 denied:
937         DEBUG(2,(__location__ ": Denied RODC secret replication for %s by RODC %s\n",
938                  ldb_dn_get_linearized(obj_dn), ldb_dn_get_linearized(rodc_res->msgs[0]->dn)));
939         ctr6->extended_ret = DRSUAPI_EXOP_ERR_NONE;
940         return WERR_DS_DRA_ACCESS_DENIED;
941
942 allowed:
943         DEBUG(2,(__location__ ": Allowed RODC secret replication for %s by RODC %s\n",
944                  ldb_dn_get_linearized(obj_dn), ldb_dn_get_linearized(rodc_res->msgs[0]->dn)));
945         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
946         req10->highwatermark.highest_usn = 0;
947         return WERR_OK;
948
949 failed:
950         DEBUG(2,(__location__ ": Failed RODC secret replication for %s by RODC %s\n",
951                  ldb_dn_get_linearized(obj_dn), dom_sid_string(mem_ctx, user_sid)));
952         ctr6->extended_ret = DRSUAPI_EXOP_ERR_NONE;
953         return WERR_DS_DRA_BAD_DN;
954 }
955
956
957 /*
958   handle a DRSUAPI_EXOP_REPL_OBJ call
959  */
960 static WERROR getncchanges_repl_obj(struct drsuapi_bind_state *b_state,
961                                     TALLOC_CTX *mem_ctx,
962                                     struct drsuapi_DsGetNCChangesRequest10 *req10,
963                                     struct dom_sid *user_sid,
964                                     struct drsuapi_DsGetNCChangesCtr6 *ctr6)
965 {
966         struct drsuapi_DsReplicaObjectIdentifier *ncRoot = req10->naming_context;
967
968         DEBUG(3,(__location__ ": DRSUAPI_EXOP_REPL_OBJ extended op on %s\n",
969                  drs_ObjectIdentifier_to_string(mem_ctx, ncRoot)));
970
971         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
972         req10->highwatermark.highest_usn = 0;
973         return WERR_OK;
974 }
975
976
977 /*
978   handle DRSUAPI_EXOP_FSMO_REQ_ROLE,
979   DRSUAPI_EXOP_FSMO_RID_REQ_ROLE,
980   and DRSUAPI_EXOP_FSMO_REQ_PDC calls
981  */
982 static WERROR getncchanges_change_master(struct drsuapi_bind_state *b_state,
983                                          TALLOC_CTX *mem_ctx,
984                                          struct drsuapi_DsGetNCChangesRequest10 *req10,
985                                          struct drsuapi_DsGetNCChangesCtr6 *ctr6)
986 {
987         struct ldb_dn *fsmo_role_dn, *req_dn, *ntds_dn;
988         int ret;
989         unsigned int i;
990         struct ldb_context *ldb = b_state->sam_ctx;
991         struct ldb_message *msg;
992
993         /*
994           steps:
995             - verify that the client dn exists
996             - verify that we are the current master
997          */
998
999         req_dn = drs_ObjectIdentifier_to_dn(mem_ctx, ldb, req10->naming_context);
1000         if (!ldb_dn_validate(req_dn)) {
1001                 /* that is not a valid dn */
1002                 DEBUG(0,(__location__ ": FSMO role transfer request for invalid DN %s\n",
1003                          drs_ObjectIdentifier_to_string(mem_ctx, req10->naming_context)));
1004                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_MISMATCH;
1005                 return WERR_OK;
1006         }
1007
1008         /* retrieve the current role owner */
1009         ret = samdb_reference_dn(ldb, mem_ctx, req_dn, "fSMORoleOwner", &fsmo_role_dn);
1010         if (ret != LDB_SUCCESS) {
1011                 DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in context - %s\n",
1012                          ldb_errstring(ldb)));
1013                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
1014                 return WERR_DS_DRA_INTERNAL_ERROR;
1015         }
1016
1017         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), fsmo_role_dn) != 0) {
1018                 /* we're not the current owner - go away */
1019                 DEBUG(0,(__location__ ": FSMO transfer request when not owner\n"));
1020                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER;
1021                 return WERR_OK;
1022         }
1023
1024         /* change the current master */
1025         msg = ldb_msg_new(ldb);
1026         W_ERROR_HAVE_NO_MEMORY(msg);
1027         msg->dn = drs_ObjectIdentifier_to_dn(msg, ldb, req10->naming_context);
1028         W_ERROR_HAVE_NO_MEMORY(msg->dn);
1029
1030         /* TODO: make sure ntds_dn is a valid nTDSDSA object */
1031         ret = dsdb_find_dn_by_guid(ldb, msg, &req10->destination_dsa_guid, &ntds_dn);
1032         if (ret != LDB_SUCCESS) {
1033                 DEBUG(0, (__location__ ": Unable to find NTDS object for guid %s - %s\n",
1034                           GUID_string(mem_ctx, &req10->destination_dsa_guid), ldb_errstring(ldb)));
1035                 talloc_free(msg);
1036                 ctr6->extended_ret = DRSUAPI_EXOP_ERR_UNKNOWN_CALLER;
1037                 return WERR_OK;
1038         }
1039
1040         ret = ldb_msg_add_string(msg, "fSMORoleOwner", ldb_dn_get_linearized(ntds_dn));
1041         if (ret != 0) {
1042                 talloc_free(msg);
1043                 return WERR_DS_DRA_INTERNAL_ERROR;
1044         }
1045
1046         for (i=0;i<msg->num_elements;i++) {
1047                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
1048         }
1049
1050         ret = ldb_transaction_start(ldb);
1051         if (ret != LDB_SUCCESS) {
1052                 DEBUG(0,(__location__ ": Failed transaction start - %s\n",
1053                          ldb_errstring(ldb)));
1054                 return WERR_DS_DRA_INTERNAL_ERROR;
1055         }
1056
1057         ret = ldb_modify(ldb, msg);
1058         if (ret != LDB_SUCCESS) {
1059                 DEBUG(0,(__location__ ": Failed to change current owner - %s\n",
1060                          ldb_errstring(ldb)));
1061                 ldb_transaction_cancel(ldb);
1062                 return WERR_DS_DRA_INTERNAL_ERROR;
1063         }
1064
1065         ret = ldb_transaction_commit(ldb);
1066         if (ret != LDB_SUCCESS) {
1067                 DEBUG(0,(__location__ ": Failed transaction commit - %s\n",
1068                          ldb_errstring(ldb)));
1069                 return WERR_DS_DRA_INTERNAL_ERROR;
1070         }
1071
1072         ctr6->extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
1073
1074         return WERR_OK;
1075 }
1076
1077 /* state of a partially completed getncchanges call */
1078 struct drsuapi_getncchanges_state {
1079         struct GUID *guids;
1080         uint32_t num_records;
1081         uint32_t num_processed;
1082         struct ldb_dn *ncRoot_dn;
1083         bool is_schema_nc;
1084         uint64_t min_usn;
1085         uint64_t highest_usn;
1086         struct ldb_dn *last_dn;
1087         struct drsuapi_DsReplicaLinkedAttribute *la_list;
1088         uint32_t la_count;
1089         bool la_sorted;
1090         uint32_t la_idx;
1091         struct drsuapi_DsReplicaCursorCtrEx *uptodateness_vector;
1092 };
1093
1094 /*
1095   see if this getncchanges request includes a request to reveal secret information
1096  */
1097 static WERROR dcesrv_drsuapi_is_reveal_secrets_request(struct drsuapi_bind_state *b_state,
1098                                                        struct drsuapi_DsGetNCChangesRequest10 *req10,
1099                                                        bool *is_secret_request)
1100 {
1101         enum drsuapi_DsExtendedOperation exop;
1102         uint32_t i;
1103         struct dsdb_schema *schema;
1104
1105         *is_secret_request = true;
1106
1107         exop = req10->extended_op;
1108
1109         switch (exop) {
1110         case DRSUAPI_EXOP_FSMO_REQ_ROLE:
1111         case DRSUAPI_EXOP_FSMO_RID_ALLOC:
1112         case DRSUAPI_EXOP_FSMO_RID_REQ_ROLE:
1113         case DRSUAPI_EXOP_FSMO_REQ_PDC:
1114         case DRSUAPI_EXOP_FSMO_ABANDON_ROLE:
1115                 /* FSMO exops can reveal secrets */
1116                 *is_secret_request = true;
1117                 return WERR_OK;
1118         case DRSUAPI_EXOP_REPL_SECRET:
1119         case DRSUAPI_EXOP_REPL_OBJ:
1120         case DRSUAPI_EXOP_NONE:
1121                 break;
1122         }
1123
1124         if (req10->replica_flags & DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING) {
1125                 *is_secret_request = false;
1126                 return WERR_OK;
1127         }
1128
1129         if (exop == DRSUAPI_EXOP_REPL_SECRET ||
1130             req10->partial_attribute_set == NULL) {
1131                 /* they want secrets */
1132                 *is_secret_request = true;
1133                 return WERR_OK;
1134         }
1135
1136         schema = dsdb_get_schema(b_state->sam_ctx, NULL);
1137
1138         /* check the attributes they asked for */
1139         for (i=0; i<req10->partial_attribute_set->num_attids; i++) {
1140                 const struct dsdb_attribute *sa;
1141                 sa = dsdb_attribute_by_attributeID_id(schema, req10->partial_attribute_set->attids[i]);
1142                 if (sa == NULL) {
1143                         return WERR_DS_DRA_SCHEMA_MISMATCH;
1144                 }
1145                 if (!dsdb_attr_in_rodc_fas(sa)) {
1146                         *is_secret_request = true;
1147                         return WERR_OK;
1148                 }
1149         }
1150
1151         /* check the attributes they asked for */
1152         for (i=0; i<req10->partial_attribute_set_ex->num_attids; i++) {
1153                 const struct dsdb_attribute *sa;
1154                 sa = dsdb_attribute_by_attributeID_id(schema, req10->partial_attribute_set_ex->attids[i]);
1155                 if (sa == NULL) {
1156                         return WERR_DS_DRA_SCHEMA_MISMATCH;
1157                 }
1158                 if (!dsdb_attr_in_rodc_fas(sa)) {
1159                         *is_secret_request = true;
1160                         return WERR_OK;
1161                 }
1162         }
1163
1164         *is_secret_request = false;
1165         return WERR_OK;
1166 }
1167
1168
1169 /*
1170   map from req8 to req10
1171  */
1172 static struct drsuapi_DsGetNCChangesRequest10 *
1173 getncchanges_map_req8(TALLOC_CTX *mem_ctx,
1174                       struct drsuapi_DsGetNCChangesRequest8 *req8)
1175 {
1176         struct drsuapi_DsGetNCChangesRequest10 *req10 = talloc_zero(mem_ctx,
1177                                                                     struct drsuapi_DsGetNCChangesRequest10);
1178         if (req10 == NULL) {
1179                 return NULL;
1180         }
1181
1182         req10->destination_dsa_guid = req8->destination_dsa_guid;
1183         req10->source_dsa_invocation_id = req8->source_dsa_invocation_id;
1184         req10->naming_context = req8->naming_context;
1185         req10->highwatermark = req8->highwatermark;
1186         req10->uptodateness_vector = req8->uptodateness_vector;
1187         req10->replica_flags = req8->replica_flags;
1188         req10->max_object_count = req8->max_object_count;
1189         req10->max_ndr_size = req8->max_ndr_size;
1190         req10->extended_op = req8->extended_op;
1191         req10->fsmo_info = req8->fsmo_info;
1192         req10->partial_attribute_set = req8->partial_attribute_set;
1193         req10->partial_attribute_set_ex = req8->partial_attribute_set_ex;
1194         req10->mapping_ctr = req8->mapping_ctr;
1195
1196         return req10;
1197 }
1198
1199
1200 /**
1201  * Collects object for normal replication cycle.
1202  */
1203 static WERROR getncchanges_collect_objects(struct drsuapi_bind_state *b_state,
1204                                            TALLOC_CTX *mem_ctx,
1205                                            struct drsuapi_DsGetNCChangesRequest10 *req10,
1206                                            struct ldb_dn *search_dn,
1207                                            const char *extra_filter,
1208                                            struct ldb_result **search_res)
1209 {
1210         int ret;
1211         char* search_filter;
1212         enum ldb_scope scope = LDB_SCOPE_SUBTREE;
1213         //const char *extra_filter;
1214         struct drsuapi_getncchanges_state *getnc_state = b_state->getncchanges_state;
1215         const char *attrs[] = { "uSNChanged",
1216                                 "objectGUID" ,
1217                                 NULL };
1218
1219         if (req10->extended_op == DRSUAPI_EXOP_REPL_OBJ ||
1220             req10->extended_op == DRSUAPI_EXOP_REPL_SECRET) {
1221                 scope = LDB_SCOPE_BASE;
1222         }
1223
1224         //extra_filter = lpcfg_parm_string(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "object filter");
1225
1226         //getnc_state->min_usn = req10->highwatermark.highest_usn;
1227
1228         /* Construct response. */
1229         search_filter = talloc_asprintf(mem_ctx,
1230                                         "(uSNChanged>=%llu)",
1231                                         (unsigned long long)(getnc_state->min_usn+1));
1232
1233         if (extra_filter) {
1234                 search_filter = talloc_asprintf(mem_ctx, "(&%s(%s))", search_filter, extra_filter);
1235         }
1236
1237         if (req10->replica_flags & DRSUAPI_DRS_CRITICAL_ONLY) {
1238                 search_filter = talloc_asprintf(mem_ctx,
1239                                                 "(&%s(isCriticalSystemObject=TRUE))",
1240                                                 search_filter);
1241         }
1242
1243         if (req10->replica_flags & DRSUAPI_DRS_ASYNC_REP) {
1244                 scope = LDB_SCOPE_BASE;
1245         }
1246
1247         if (!search_dn) {
1248                 search_dn = getnc_state->ncRoot_dn;
1249         }
1250
1251         DEBUG(2,(__location__ ": getncchanges on %s using filter %s\n",
1252                  ldb_dn_get_linearized(getnc_state->ncRoot_dn), search_filter));
1253         ret = drsuapi_search_with_extended_dn(b_state->sam_ctx, getnc_state, search_res,
1254                                               search_dn, scope, attrs,
1255                                               search_filter);
1256         if (ret != LDB_SUCCESS) {
1257                 return WERR_DS_DRA_INTERNAL_ERROR;
1258         }
1259
1260         return WERR_OK;
1261 }
1262
1263 /**
1264  * Collects object for normal replication cycle.
1265  */
1266 static WERROR getncchanges_collect_objects_exop(struct drsuapi_bind_state *b_state,
1267                                                 TALLOC_CTX *mem_ctx,
1268                                                 struct drsuapi_DsGetNCChangesRequest10 *req10,
1269                                                 struct drsuapi_DsGetNCChangesCtr6 *ctr6,
1270                                                 struct ldb_dn *search_dn,
1271                                                 const char *extra_filter,
1272                                                 struct ldb_result **search_res)
1273 {
1274         /* we have nothing to do in case of ex-op failure */
1275         if (ctr6->extended_ret != DRSUAPI_EXOP_ERR_SUCCESS) {
1276                 return WERR_OK;
1277         }
1278
1279         /* TODO: implement extended op specific collection
1280          * of objects. Right now we just normal procedure
1281          * for collecting objects */
1282         return getncchanges_collect_objects(b_state, mem_ctx, req10, search_dn, extra_filter, search_res);
1283 }
1284
1285 /* 
1286   drsuapi_DsGetNCChanges
1287
1288   see MS-DRSR 4.1.10.5.2 for basic logic of this function
1289 */
1290 WERROR dcesrv_drsuapi_DsGetNCChanges(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
1291                                      struct drsuapi_DsGetNCChanges *r)
1292 {
1293         struct drsuapi_DsReplicaObjectIdentifier *ncRoot;
1294         int ret;
1295         uint32_t i;
1296         struct dsdb_schema *schema;
1297         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
1298         struct drsuapi_DsReplicaObjectListItemEx **currentObject;
1299         NTSTATUS status;
1300         DATA_BLOB session_key;
1301         WERROR werr;
1302         struct dcesrv_handle *h;
1303         struct drsuapi_bind_state *b_state;     
1304         struct drsuapi_getncchanges_state *getnc_state;
1305         struct drsuapi_DsGetNCChangesRequest10 *req10;
1306         uint32_t options;
1307         uint32_t max_objects;
1308         uint32_t max_links;
1309         uint32_t link_count = 0;
1310         uint32_t link_total = 0;
1311         uint32_t link_given = 0;
1312         struct ldb_dn *search_dn = NULL;
1313         bool am_rodc, null_scope=false;
1314         enum security_user_level security_level;
1315         struct ldb_context *sam_ctx;
1316         struct dom_sid *user_sid;
1317         bool is_secret_request;
1318
1319         DCESRV_PULL_HANDLE_WERR(h, r->in.bind_handle, DRSUAPI_BIND_HANDLE);
1320         b_state = h->data;
1321
1322         sam_ctx = b_state->sam_ctx_system?b_state->sam_ctx_system:b_state->sam_ctx;
1323
1324         *r->out.level_out = 6;
1325         /* TODO: linked attributes*/
1326         r->out.ctr->ctr6.linked_attributes_count = 0;
1327         r->out.ctr->ctr6.linked_attributes = NULL;
1328
1329         r->out.ctr->ctr6.object_count = 0;
1330         r->out.ctr->ctr6.nc_object_count = 0;
1331         r->out.ctr->ctr6.more_data = false;
1332         r->out.ctr->ctr6.uptodateness_vector = NULL;
1333
1334         /* a RODC doesn't allow for any replication */
1335         ret = samdb_rodc(sam_ctx, &am_rodc);
1336         if (ret == LDB_SUCCESS && am_rodc) {
1337                 DEBUG(0,(__location__ ": DsGetNCChanges attempt on RODC\n"));
1338                 return WERR_DS_DRA_SOURCE_DISABLED;
1339         }
1340
1341         /* Check request revision. 
1342          */
1343         switch (r->in.level) {
1344         case 8:
1345                 req10 = getncchanges_map_req8(mem_ctx, &r->in.req->req8);
1346                 if (req10 == NULL) {
1347                         return WERR_NOMEM;
1348                 }
1349                 break;
1350         case 10:
1351                 req10 = &r->in.req->req10;
1352                 break;
1353         default:
1354                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with unsupported level %u\n",
1355                          r->in.level));
1356                 return WERR_REVISION_MISMATCH;
1357         }
1358
1359
1360         /* Perform access checks. */
1361         /* TODO: we need to support a sync on a specific non-root
1362          * DN. We'll need to find the real partition root here */
1363         ncRoot = req10->naming_context;
1364         if (ncRoot == NULL) {
1365                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with no NC\n"));
1366                 return WERR_DS_DRA_INVALID_PARAMETER;
1367         }
1368
1369         if (samdb_ntds_options(sam_ctx, &options) != LDB_SUCCESS) {
1370                 return WERR_DS_DRA_INTERNAL_ERROR;
1371         }
1372         
1373         if ((options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) &&
1374             !(req10->replica_flags & DRSUAPI_DRS_SYNC_FORCED)) {
1375                 return WERR_DS_DRA_SOURCE_DISABLED;
1376         }
1377
1378         user_sid = &dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
1379
1380         werr = drs_security_access_check_nc_root(b_state->sam_ctx,
1381                                                  mem_ctx,
1382                                                  dce_call->conn->auth_state.session_info->security_token,
1383                                                  req10->naming_context,
1384                                                  GUID_DRS_GET_CHANGES);
1385         if (!W_ERROR_IS_OK(werr)) {
1386                 return werr;
1387         }
1388
1389         werr = dcesrv_drsuapi_is_reveal_secrets_request(b_state, req10, &is_secret_request);
1390         if (!W_ERROR_IS_OK(werr)) {
1391                 return werr;
1392         }
1393         if (is_secret_request && req10->extended_op != DRSUAPI_EXOP_REPL_SECRET) {
1394                 werr = drs_security_access_check_nc_root(b_state->sam_ctx,
1395                                                          mem_ctx,
1396                                                          dce_call->conn->auth_state.session_info->security_token,
1397                                                          req10->naming_context,
1398                                                          GUID_DRS_GET_ALL_CHANGES);
1399                 if (!W_ERROR_IS_OK(werr)) {
1400                         return werr;
1401                 }
1402         }
1403
1404         /* for non-administrator replications, check that they have
1405            given the correct source_dsa_invocation_id */
1406         security_level = security_session_user_level(dce_call->conn->auth_state.session_info,
1407                                                      samdb_domain_sid(sam_ctx));
1408         if (security_level == SECURITY_RO_DOMAIN_CONTROLLER) {
1409                 if (req10->replica_flags & DRSUAPI_DRS_WRIT_REP) {
1410                         /* we rely on this flag being unset for RODC requests */
1411                         req10->replica_flags &= ~DRSUAPI_DRS_WRIT_REP;
1412                 }
1413         }
1414
1415         if (req10->replica_flags & DRSUAPI_DRS_FULL_SYNC_PACKET) {
1416                 /* Ignore the _in_ uptpdateness vector*/
1417                 req10->uptodateness_vector = NULL;
1418         } 
1419
1420         getnc_state = b_state->getncchanges_state;
1421
1422         /* see if a previous replication has been abandoned */
1423         if (getnc_state) {
1424                 struct ldb_dn *new_dn = drs_ObjectIdentifier_to_dn(getnc_state, sam_ctx, ncRoot);
1425                 if (ldb_dn_compare(new_dn, getnc_state->ncRoot_dn) != 0) {
1426                         DEBUG(0,(__location__ ": DsGetNCChanges 2nd replication on different DN %s %s (last_dn %s)\n",
1427                                  ldb_dn_get_linearized(new_dn),
1428                                  ldb_dn_get_linearized(getnc_state->ncRoot_dn),
1429                                  ldb_dn_get_linearized(getnc_state->last_dn)));
1430                         talloc_free(getnc_state);
1431                         getnc_state = NULL;
1432                 }
1433         }
1434
1435         if (getnc_state == NULL) {
1436                 getnc_state = talloc_zero(b_state, struct drsuapi_getncchanges_state);
1437                 if (getnc_state == NULL) {
1438                         return WERR_NOMEM;
1439                 }
1440                 b_state->getncchanges_state = getnc_state;
1441                 getnc_state->ncRoot_dn = drs_ObjectIdentifier_to_dn(getnc_state, sam_ctx, ncRoot);
1442
1443                 /* find out if we are to replicate Schema NC */
1444                 ret = ldb_dn_compare(getnc_state->ncRoot_dn,
1445                                      ldb_get_schema_basedn(b_state->sam_ctx));
1446                 getnc_state->is_schema_nc = (0 == ret);
1447
1448                 if (req10->extended_op != DRSUAPI_EXOP_NONE) {
1449                         r->out.ctr->ctr6.extended_ret = DRSUAPI_EXOP_ERR_SUCCESS;
1450                 }
1451
1452                 /*
1453                  * This is the first replication cycle and it is
1454                  * a good place to handle extended operations
1455                  *
1456                  * FIXME: we don't fully support extended operations yet
1457                  */
1458                 switch (req10->extended_op) {
1459                 case DRSUAPI_EXOP_NONE:
1460                         break;
1461                 case DRSUAPI_EXOP_FSMO_RID_ALLOC:
1462                         werr = getncchanges_rid_alloc(b_state, mem_ctx, req10, &r->out.ctr->ctr6);
1463                         W_ERROR_NOT_OK_RETURN(werr);
1464                         search_dn = ldb_get_default_basedn(sam_ctx);
1465                         break;
1466                 case DRSUAPI_EXOP_REPL_SECRET:
1467                         werr = getncchanges_repl_secret(b_state, mem_ctx, req10, user_sid, &r->out.ctr->ctr6);
1468                         r->out.result = werr;
1469                         W_ERROR_NOT_OK_RETURN(werr);
1470                         break;
1471                 case DRSUAPI_EXOP_FSMO_REQ_ROLE:
1472                         werr = getncchanges_change_master(b_state, mem_ctx, req10, &r->out.ctr->ctr6);
1473                         W_ERROR_NOT_OK_RETURN(werr);
1474                         break;
1475                 case DRSUAPI_EXOP_FSMO_RID_REQ_ROLE:
1476                         werr = getncchanges_change_master(b_state, mem_ctx, req10, &r->out.ctr->ctr6);
1477                         W_ERROR_NOT_OK_RETURN(werr);
1478                         break;
1479                 case DRSUAPI_EXOP_FSMO_REQ_PDC:
1480                         werr = getncchanges_change_master(b_state, mem_ctx, req10, &r->out.ctr->ctr6);
1481                         W_ERROR_NOT_OK_RETURN(werr);
1482                         break;
1483                 case DRSUAPI_EXOP_REPL_OBJ:
1484                         werr = getncchanges_repl_obj(b_state, mem_ctx, req10, user_sid, &r->out.ctr->ctr6);
1485                         r->out.result = werr;
1486                         W_ERROR_NOT_OK_RETURN(werr);
1487                         break;
1488
1489                 case DRSUAPI_EXOP_FSMO_ABANDON_ROLE:
1490
1491                         DEBUG(0,(__location__ ": Request for DsGetNCChanges unsupported extended op 0x%x\n",
1492                                  (unsigned)req10->extended_op));
1493                         return WERR_DS_DRA_NOT_SUPPORTED;
1494                 }
1495         }
1496
1497         if (!ldb_dn_validate(getnc_state->ncRoot_dn) ||
1498             ldb_dn_is_null(getnc_state->ncRoot_dn)) {
1499                 DEBUG(0,(__location__ ": Bad DN '%s'\n",
1500                          drs_ObjectIdentifier_to_string(mem_ctx, ncRoot)));
1501                 return WERR_DS_DRA_INVALID_PARAMETER;
1502         }
1503
1504         /* we need the session key for encrypting password attributes */
1505         status = dcesrv_inherited_session_key(dce_call->conn, &session_key);
1506         if (!NT_STATUS_IS_OK(status)) {
1507                 DEBUG(0,(__location__ ": Failed to get session key\n"));
1508                 return WERR_DS_DRA_INTERNAL_ERROR;              
1509         }
1510
1511         /* 
1512            TODO: MS-DRSR section 4.1.10.1.1
1513            Work out if this is the start of a new cycle */
1514
1515         if (getnc_state->guids == NULL) {
1516                 const char *extra_filter;
1517                 struct ldb_result *search_res = NULL;
1518
1519                 extra_filter = lpcfg_parm_string(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "object filter");
1520
1521                 getnc_state->min_usn = req10->highwatermark.highest_usn;
1522
1523                 if (req10->extended_op == DRSUAPI_EXOP_NONE) {
1524                         werr = getncchanges_collect_objects(b_state, mem_ctx, req10,
1525                                                             search_dn, extra_filter,
1526                                                             &search_res);
1527                 } else {
1528                         werr = getncchanges_collect_objects_exop(b_state, mem_ctx, req10,
1529                                                                  &r->out.ctr->ctr6,
1530                                                                  search_dn, extra_filter,
1531                                                                  &search_res);
1532                 }
1533                 W_ERROR_NOT_OK_RETURN(werr);
1534
1535                 if (search_res) {
1536                         if (req10->replica_flags & DRSUAPI_DRS_GET_ANC) {
1537                                 TYPESAFE_QSORT(search_res->msgs,
1538                                                search_res->count,
1539                                                site_res_cmp_parent_order);
1540                         } else {
1541                                 TYPESAFE_QSORT(search_res->msgs,
1542                                                search_res->count,
1543                                                site_res_cmp_usn_order);
1544                         }
1545                 }
1546
1547                 /* extract out the GUIDs list */
1548                 getnc_state->num_records = search_res ? search_res->count : 0;
1549                 getnc_state->guids = talloc_array(getnc_state, struct GUID, getnc_state->num_records);
1550                 W_ERROR_HAVE_NO_MEMORY(getnc_state->guids);
1551
1552                 for (i=0; i<getnc_state->num_records; i++) {
1553                         getnc_state->guids[i] = samdb_result_guid(search_res->msgs[i], "objectGUID");
1554                         if (GUID_all_zero(&getnc_state->guids[i])) {
1555                                 DEBUG(2,("getncchanges: bad objectGUID from %s\n", ldb_dn_get_linearized(search_res->msgs[i]->dn)));
1556                                 return WERR_DS_DRA_INTERNAL_ERROR;
1557                         }
1558                 }
1559
1560
1561                 talloc_free(search_res);
1562
1563                 getnc_state->uptodateness_vector = talloc_steal(getnc_state, req10->uptodateness_vector);
1564                 if (getnc_state->uptodateness_vector) {
1565                         /* make sure its sorted */
1566                         TYPESAFE_QSORT(getnc_state->uptodateness_vector->cursors,
1567                                        getnc_state->uptodateness_vector->count,
1568                                        drsuapi_DsReplicaCursor_compare);
1569                 }
1570         }
1571
1572         /* Prefix mapping */
1573         schema = dsdb_get_schema(sam_ctx, mem_ctx);
1574         if (!schema) {
1575                 DEBUG(0,("No schema in sam_ctx\n"));
1576                 return WERR_DS_DRA_INTERNAL_ERROR;
1577         }
1578
1579         r->out.ctr->ctr6.naming_context = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
1580         *r->out.ctr->ctr6.naming_context = *ncRoot;
1581
1582         if (dsdb_find_guid_by_dn(sam_ctx, getnc_state->ncRoot_dn,
1583                                  &r->out.ctr->ctr6.naming_context->guid) != LDB_SUCCESS) {
1584                 DEBUG(0,(__location__ ": Failed to find GUID of ncRoot_dn %s\n",
1585                          ldb_dn_get_linearized(getnc_state->ncRoot_dn)));
1586                 return WERR_DS_DRA_INTERNAL_ERROR;
1587         }
1588
1589         /* find the SID if there is one */
1590         dsdb_find_sid_by_dn(sam_ctx, getnc_state->ncRoot_dn, &r->out.ctr->ctr6.naming_context->sid);
1591
1592         dsdb_get_oid_mappings_drsuapi(schema, true, mem_ctx, &ctr);
1593         r->out.ctr->ctr6.mapping_ctr = *ctr;
1594
1595         r->out.ctr->ctr6.source_dsa_guid = *(samdb_ntds_objectGUID(sam_ctx));
1596         r->out.ctr->ctr6.source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
1597
1598         r->out.ctr->ctr6.old_highwatermark = req10->highwatermark;
1599         r->out.ctr->ctr6.new_highwatermark = req10->highwatermark;
1600
1601         r->out.ctr->ctr6.first_object = NULL;
1602         currentObject = &r->out.ctr->ctr6.first_object;
1603
1604         /* use this to force single objects at a time, which is useful
1605          * for working out what object is giving problems
1606          */
1607         max_objects = lpcfg_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max object sync", 1000);
1608         if (req10->max_object_count < max_objects) {
1609                 max_objects = req10->max_object_count;
1610         }
1611         /*
1612          * TODO: work out how the maximum should be calculated
1613          */
1614         max_links = lpcfg_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max link sync", 1500);
1615
1616         for (i=getnc_state->num_processed;
1617              i<getnc_state->num_records &&
1618                      !null_scope &&
1619                      (r->out.ctr->ctr6.object_count < max_objects);
1620             i++) {
1621                 int uSN;
1622                 struct drsuapi_DsReplicaObjectListItemEx *obj;
1623                 struct ldb_message *msg;
1624                 static const char * const msg_attrs[] = {
1625                                             "*",
1626                                             "nTSecurityDescriptor",
1627                                             "parentGUID",
1628                                             "replPropertyMetaData",
1629                                             DSDB_SECRET_ATTRIBUTES,
1630                                             NULL };
1631                 struct ldb_result *msg_res;
1632                 struct ldb_dn *msg_dn;
1633
1634                 obj = talloc_zero(mem_ctx, struct drsuapi_DsReplicaObjectListItemEx);
1635                 W_ERROR_HAVE_NO_MEMORY(obj);
1636
1637                 msg_dn = ldb_dn_new_fmt(obj, sam_ctx, "<GUID=%s>", GUID_string(obj, &getnc_state->guids[i]));
1638                 W_ERROR_HAVE_NO_MEMORY(msg_dn);
1639
1640
1641                 /* by re-searching here we avoid having a lot of full
1642                  * records in memory between calls to getncchanges
1643                  */
1644                 ret = drsuapi_search_with_extended_dn(sam_ctx, obj, &msg_res,
1645                                                       msg_dn,
1646                                                       LDB_SCOPE_BASE, msg_attrs, NULL);
1647                 if (ret != LDB_SUCCESS) {
1648                         if (ret != LDB_ERR_NO_SUCH_OBJECT) {
1649                                 DEBUG(1,("getncchanges: failed to fetch DN %s - %s\n",
1650                                          ldb_dn_get_extended_linearized(obj, msg_dn, 1), ldb_errstring(sam_ctx)));
1651                         }
1652                         talloc_free(obj);
1653                         continue;
1654                 }
1655
1656                 msg = msg_res->msgs[0];
1657
1658                 werr = get_nc_changes_build_object(obj, msg,
1659                                                    sam_ctx, getnc_state->ncRoot_dn,
1660                                                    getnc_state->is_schema_nc,
1661                                                    schema, &session_key, getnc_state->min_usn,
1662                                                    req10->replica_flags,
1663                                                    req10->partial_attribute_set,
1664                                                    getnc_state->uptodateness_vector,
1665                                                    req10->extended_op);
1666                 if (!W_ERROR_IS_OK(werr)) {
1667                         return werr;
1668                 }
1669
1670                 werr = get_nc_changes_add_links(sam_ctx, getnc_state,
1671                                                 getnc_state->ncRoot_dn,
1672                                                 schema, getnc_state->min_usn,
1673                                                 req10->replica_flags,
1674                                                 msg,
1675                                                 &getnc_state->la_list,
1676                                                 &getnc_state->la_count,
1677                                                 getnc_state->uptodateness_vector);
1678                 if (!W_ERROR_IS_OK(werr)) {
1679                         return werr;
1680                 }
1681
1682                 uSN = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
1683                 if (uSN > r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn) {
1684                         r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn = uSN;
1685                 }
1686                 if (uSN > getnc_state->highest_usn) {
1687                         getnc_state->highest_usn = uSN;
1688                 }
1689
1690                 if (obj->meta_data_ctr == NULL) {
1691                         DEBUG(8,(__location__ ": getncchanges skipping send of object %s\n",
1692                                  ldb_dn_get_linearized(msg->dn)));
1693                         /* no attributes to send */
1694                         talloc_free(obj);
1695                         continue;
1696                 }
1697
1698                 r->out.ctr->ctr6.object_count++;
1699                 
1700                 *currentObject = obj;
1701                 currentObject = &obj->next_object;
1702
1703                 talloc_free(getnc_state->last_dn);
1704                 getnc_state->last_dn = ldb_dn_copy(getnc_state, msg->dn);
1705
1706                 DEBUG(8,(__location__ ": replicating object %s\n", ldb_dn_get_linearized(msg->dn)));
1707
1708                 talloc_free(msg_res);
1709                 talloc_free(msg_dn);
1710         }
1711
1712         getnc_state->num_processed = i;
1713
1714         r->out.ctr->ctr6.nc_object_count = getnc_state->num_records;
1715
1716         /* the client can us to call UpdateRefs on its behalf to
1717            re-establish monitoring of the NC */
1718         if ((req10->replica_flags & (DRSUAPI_DRS_ADD_REF | DRSUAPI_DRS_REF_GCSPN)) &&
1719             !GUID_all_zero(&req10->destination_dsa_guid)) {
1720                 struct drsuapi_DsReplicaUpdateRefsRequest1 ureq;
1721                 DEBUG(3,("UpdateRefs on getncchanges for %s\n",
1722                          GUID_string(mem_ctx, &req10->destination_dsa_guid)));
1723                 ureq.naming_context = ncRoot;
1724                 ureq.dest_dsa_dns_name = talloc_asprintf(mem_ctx, "%s._msdcs.%s",
1725                                                          GUID_string(mem_ctx, &req10->destination_dsa_guid),
1726                                                          lpcfg_dnsdomain(dce_call->conn->dce_ctx->lp_ctx));
1727                 if (!ureq.dest_dsa_dns_name) {
1728                         return WERR_NOMEM;
1729                 }
1730                 ureq.dest_dsa_guid = req10->destination_dsa_guid;
1731                 ureq.options = DRSUAPI_DRS_ADD_REF |
1732                         DRSUAPI_DRS_ASYNC_OP |
1733                         DRSUAPI_DRS_GETCHG_CHECK;
1734
1735                 /* we also need to pass through the
1736                    DRSUAPI_DRS_REF_GCSPN bit so that repsTo gets flagged
1737                    to send notifies using the GC SPN */
1738                 ureq.options |= (req10->replica_flags & DRSUAPI_DRS_REF_GCSPN);
1739
1740                 werr = drsuapi_UpdateRefs(b_state, mem_ctx, &ureq);
1741                 if (!W_ERROR_IS_OK(werr)) {
1742                         DEBUG(0,(__location__ ": Failed UpdateRefs in DsGetNCChanges - %s\n",
1743                                  win_errstr(werr)));
1744                 }
1745         }
1746
1747         /*
1748          * TODO:
1749          * This is just a guess, how to calculate the
1750          * number of linked attributes to send, we need to
1751          * find out how to do this right.
1752          */
1753         if (r->out.ctr->ctr6.object_count >= max_links) {
1754                 max_links = 0;
1755         } else {
1756                 max_links -= r->out.ctr->ctr6.object_count;
1757         }
1758
1759         link_total = getnc_state->la_count;
1760
1761         if (i < getnc_state->num_records) {
1762                 r->out.ctr->ctr6.more_data = true;
1763         } else {
1764                 /* sort the whole array the first time */
1765                 if (!getnc_state->la_sorted) {
1766                         LDB_TYPESAFE_QSORT(getnc_state->la_list, getnc_state->la_count,
1767                                            sam_ctx, linked_attribute_compare);
1768                         getnc_state->la_sorted = true;
1769                 }
1770
1771                 link_count = getnc_state->la_count - getnc_state->la_idx;
1772                 link_count = MIN(max_links, link_count);
1773
1774                 r->out.ctr->ctr6.linked_attributes_count = link_count;
1775                 r->out.ctr->ctr6.linked_attributes = getnc_state->la_list + getnc_state->la_idx;
1776
1777                 getnc_state->la_idx += link_count;
1778                 link_given = getnc_state->la_idx;
1779
1780                 if (getnc_state->la_idx < getnc_state->la_count) {
1781                         r->out.ctr->ctr6.more_data = true;
1782                 }
1783         }
1784
1785         if (!r->out.ctr->ctr6.more_data) {
1786                 talloc_steal(mem_ctx, getnc_state->la_list);
1787
1788                 r->out.ctr->ctr6.uptodateness_vector = talloc(mem_ctx, struct drsuapi_DsReplicaCursor2CtrEx);
1789                 r->out.ctr->ctr6.new_highwatermark.highest_usn = r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn;
1790
1791                 werr = get_nc_changes_udv(sam_ctx, getnc_state->ncRoot_dn,
1792                                           r->out.ctr->ctr6.uptodateness_vector);
1793                 if (!W_ERROR_IS_OK(werr)) {
1794                         return werr;
1795                 }
1796
1797                 talloc_free(getnc_state);
1798                 b_state->getncchanges_state = NULL;
1799         }
1800
1801         if (req10->extended_op != DRSUAPI_EXOP_NONE) {
1802                 r->out.ctr->ctr6.uptodateness_vector = NULL;
1803                 r->out.ctr->ctr6.nc_object_count = 0;
1804                 ZERO_STRUCT(r->out.ctr->ctr6.new_highwatermark);
1805         }
1806
1807         DEBUG(r->out.ctr->ctr6.more_data?4:2,
1808               ("DsGetNCChanges with uSNChanged >= %llu flags 0x%08x on %s gave %u objects (done %u/%u) %u links (done %u/%u (as %s))\n",
1809                (unsigned long long)(req10->highwatermark.highest_usn+1),
1810                req10->replica_flags, drs_ObjectIdentifier_to_string(mem_ctx, ncRoot),
1811                r->out.ctr->ctr6.object_count,
1812                i, r->out.ctr->ctr6.more_data?getnc_state->num_records:i,
1813                r->out.ctr->ctr6.linked_attributes_count,
1814                link_given, link_total,
1815                dom_sid_string(mem_ctx, user_sid)));
1816
1817 #if 0
1818         if (!r->out.ctr->ctr6.more_data && req10->extended_op != DRSUAPI_EXOP_NONE) {
1819                 NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsGetNCChanges, NDR_BOTH, r);
1820         }
1821 #endif
1822
1823         return WERR_OK;
1824 }