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