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