s4-drs: use the extended linearized form for DRS replication
[mat/samba.git] / source4 / rpc_server / drsuapi / getncchanges.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    implement the DRSUpdateRefs 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 "rpc_server/drsuapi/dcesrv_drsuapi.h"
30 #include "rpc_server/dcerpc_server_proto.h"
31 #include "../libcli/drsuapi/drsuapi.h"
32 #include "libcli/security/security.h"
33
34 /*
35   build a DsReplicaObjectIdentifier from a ldb msg
36  */
37 static struct drsuapi_DsReplicaObjectIdentifier *get_object_identifier(TALLOC_CTX *mem_ctx,
38                                                                        struct ldb_message *msg)
39 {
40         struct drsuapi_DsReplicaObjectIdentifier *identifier;
41         struct dom_sid *sid;
42
43         identifier = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
44         if (identifier == NULL) {
45                 return NULL;
46         }
47
48         identifier->dn = ldb_dn_alloc_linearized(identifier, msg->dn);
49         identifier->guid = samdb_result_guid(msg, "objectGUID");
50
51         sid = samdb_result_dom_sid(identifier, msg, "objectSid");
52         if (sid) {
53                 identifier->sid = *sid;
54         } else {
55                 ZERO_STRUCT(identifier->sid);
56         }
57         return identifier;
58 }
59
60 /* 
61   drsuapi_DsGetNCChanges for one object
62 */
63 static WERROR get_nc_changes_build_object(struct drsuapi_DsReplicaObjectListItemEx *obj,
64                                           struct ldb_message *msg,
65                                           struct ldb_context *sam_ctx,
66                                           struct ldb_dn *ncRoot_dn,
67                                           struct dsdb_schema *schema,
68                                           DATA_BLOB *session_key,
69                                           uint64_t highest_usn,
70                                           uint32_t replica_flags)
71 {
72         const struct ldb_val *md_value;
73         int i, n;
74         struct replPropertyMetaDataBlob md;
75         uint32_t rid = 0;
76         enum ndr_err_code ndr_err;
77         uint32_t *attids;
78         const char *rdn;
79         const struct dsdb_attribute *rdn_sa;
80
81         if (ldb_dn_compare(ncRoot_dn, msg->dn) == 0) {
82                 obj->is_nc_prefix = true;
83                 obj->parent_object_guid = NULL;
84         } else {
85                 obj->is_nc_prefix = false;
86                 obj->parent_object_guid = talloc(obj, struct GUID);
87                 if (obj->parent_object_guid == NULL) {
88                         return WERR_DS_DRA_INTERNAL_ERROR;
89                 }
90                 *obj->parent_object_guid = samdb_result_guid(msg, "parentGUID");
91                 if (GUID_all_zero(obj->parent_object_guid)) {
92                         DEBUG(0,(__location__ ": missing parentGUID for %s\n",
93                                  ldb_dn_get_linearized(msg->dn)));
94                         return WERR_DS_DRA_INTERNAL_ERROR;
95                 }
96         }
97         obj->next_object = NULL;
98         
99         md_value = ldb_msg_find_ldb_val(msg, "replPropertyMetaData");
100         if (!md_value) {
101                 /* nothing to send */
102                 return WERR_OK;
103         }
104
105         ndr_err = ndr_pull_struct_blob(md_value, obj,
106                                        lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")), &md,
107                                        (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
108         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
109                 return WERR_DS_DRA_INTERNAL_ERROR;
110         }
111         
112         if (md.version != 1) {
113                 return WERR_DS_DRA_INTERNAL_ERROR;
114         }
115
116         rdn = ldb_dn_get_rdn_name(msg->dn);
117         if (rdn == NULL) {
118                 DEBUG(0,(__location__ ": No rDN for %s\n", ldb_dn_get_linearized(msg->dn)));
119                 return WERR_DS_DRA_INTERNAL_ERROR;
120         }
121
122         rdn_sa = dsdb_attribute_by_lDAPDisplayName(schema, rdn);
123         if (rdn_sa == NULL) {
124                 DEBUG(0,(__location__ ": Can't find dsds_attribute for rDN %s in %s\n", 
125                          rdn, ldb_dn_get_linearized(msg->dn)));
126                 return WERR_DS_DRA_INTERNAL_ERROR;
127         }
128
129         obj->meta_data_ctr = talloc(obj, struct drsuapi_DsReplicaMetaDataCtr);
130         attids = talloc_array(obj, uint32_t, md.ctr.ctr1.count);
131
132         obj->object.identifier = get_object_identifier(obj, msg);
133         if (obj->object.identifier == NULL) {
134                 return WERR_NOMEM;
135         }
136         dom_sid_split_rid(NULL, &obj->object.identifier->sid, NULL, &rid);
137         
138         obj->meta_data_ctr->meta_data = talloc_array(obj, struct drsuapi_DsReplicaMetaData, md.ctr.ctr1.count);
139         for (n=i=0; i<md.ctr.ctr1.count; i++) {
140                 const struct dsdb_attribute *sa;
141                 /* if the attribute has not changed, and it is not the
142                    instanceType then don't include it */
143                 if (md.ctr.ctr1.array[i].local_usn < highest_usn &&
144                     md.ctr.ctr1.array[i].attid != DRSUAPI_ATTRIBUTE_instanceType) continue;
145
146                 /* don't include the rDN */
147                 if (md.ctr.ctr1.array[i].attid == rdn_sa->attributeID_id) continue;
148
149                 sa = dsdb_attribute_by_attributeID_id(schema, md.ctr.ctr1.array[i].attid);
150                 if (sa->linkID) {
151                         struct ldb_message_element *el;
152                         el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
153                         if (el && el->num_values && dsdb_dn_is_upgraded_link_val(&el->values[0])) {
154                                 /* don't send upgraded links inline */
155                                 continue;
156                         }
157                 }
158
159                 obj->meta_data_ctr->meta_data[n].originating_change_time = md.ctr.ctr1.array[i].originating_change_time;
160                 obj->meta_data_ctr->meta_data[n].version = md.ctr.ctr1.array[i].version;
161                 obj->meta_data_ctr->meta_data[n].originating_invocation_id = md.ctr.ctr1.array[i].originating_invocation_id;
162                 obj->meta_data_ctr->meta_data[n].originating_usn = md.ctr.ctr1.array[i].originating_usn;
163                 attids[n] = md.ctr.ctr1.array[i].attid;
164                 n++;
165         }
166
167         /*
168           note that if n==0 we still need to send the change, as it
169           could be a rename, which changes the uSNChanged, but not any
170           of the replicated attributes
171          */
172
173         obj->meta_data_ctr->count = n;
174
175         obj->object.flags = DRSUAPI_DS_REPLICA_OBJECT_FROM_MASTER;
176         obj->object.attribute_ctr.num_attributes = obj->meta_data_ctr->count;
177         obj->object.attribute_ctr.attributes = talloc_array(obj, struct drsuapi_DsReplicaAttribute,
178                                                             obj->object.attribute_ctr.num_attributes);
179
180         /*
181          * Note that the meta_data array and the attributes array must
182          * be the same size and in the same order
183          */
184         for (i=0; i<obj->object.attribute_ctr.num_attributes; i++) {
185                 struct ldb_message_element *el;
186                 WERROR werr;
187                 const struct dsdb_attribute *sa;
188         
189                 sa = dsdb_attribute_by_attributeID_id(schema, attids[i]);
190                 if (!sa) {
191                         DEBUG(0,("Unable to find attributeID %u in schema\n", attids[i]));
192                         return WERR_DS_DRA_INTERNAL_ERROR;
193                 }
194
195                 el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
196                 if (el == NULL) {
197                         /* this happens for attributes that have been removed */
198                         DEBUG(5,("No element '%s' for attributeID %u in message\n",
199                                  sa->lDAPDisplayName, attids[i]));
200                         ZERO_STRUCT(obj->object.attribute_ctr.attributes[i]);
201                         obj->object.attribute_ctr.attributes[i].attid = attids[i];
202                 } else {
203                         werr = dsdb_attribute_ldb_to_drsuapi(sam_ctx, schema, el, obj,
204                                                              &obj->object.attribute_ctr.attributes[i]);
205                         if (!W_ERROR_IS_OK(werr)) {
206                                 DEBUG(0,("Unable to convert %s to DRS object - %s\n", 
207                                          sa->lDAPDisplayName, win_errstr(werr)));
208                                 return werr;
209                         }
210                         /* if DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING is set
211                          * check if attribute is secret and send a null value
212                          */
213                         if (replica_flags & DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING) {
214                                 drsuapi_process_secret_attribute(&obj->object.attribute_ctr.attributes[i],
215                                                                  &obj->meta_data_ctr->meta_data[i]);
216                         }
217                         /* some attributes needs to be encrypted
218                            before being sent */
219                         werr = drsuapi_encrypt_attribute(obj, session_key, rid, 
220                                                          &obj->object.attribute_ctr.attributes[i]);
221                         if (!W_ERROR_IS_OK(werr)) {
222                                 DEBUG(0,("Unable to encrypt %s in DRS object - %s\n", 
223                                          sa->lDAPDisplayName, win_errstr(werr)));
224                                 return werr;
225                         }
226                 }
227         }
228
229         return WERR_OK;
230 }
231
232
233 /*
234   add one linked attribute from an object to the list of linked
235   attributes in a getncchanges request
236  */
237 static WERROR get_nc_changes_add_la(TALLOC_CTX *mem_ctx,
238                                     struct ldb_context *sam_ctx,
239                                     const struct dsdb_schema *schema,
240                                     const struct dsdb_attribute *sa,
241                                     struct ldb_message *msg,
242                                     struct dsdb_dn *dsdb_dn,
243                                     struct drsuapi_DsReplicaLinkedAttribute **la_list,
244                                     uint32_t *la_count)
245 {
246         struct drsuapi_DsReplicaLinkedAttribute *la;
247         bool active;
248         NTSTATUS status;
249         struct ldb_message_element val_el;
250         struct ldb_val v;
251         WERROR werr;
252         struct drsuapi_DsReplicaAttribute drs;
253
254         (*la_list) = talloc_realloc(mem_ctx, *la_list, struct drsuapi_DsReplicaLinkedAttribute, (*la_count)+1);
255         W_ERROR_HAVE_NO_MEMORY(*la_list);
256
257         la = &(*la_list)[*la_count];
258
259         la->identifier = get_object_identifier(*la_list, msg);
260         W_ERROR_HAVE_NO_MEMORY(la->identifier);
261
262         active = ldb_dn_get_extended_component(dsdb_dn->dn, "DELETED")?false:true;
263
264         la->attid = sa->attributeID_id;
265         la->flags = active?DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE:0;
266
267         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->originating_add_time, "RMD_ADDTIME");
268         if (!NT_STATUS_IS_OK(status)) {
269                 return ntstatus_to_werror(status);
270         }
271         status = dsdb_get_extended_dn_uint32(dsdb_dn->dn, &la->meta_data.version, "RMD_VERSION");
272         if (!NT_STATUS_IS_OK(status)) {
273                 return ntstatus_to_werror(status);
274         }
275         status = dsdb_get_extended_dn_nttime(dsdb_dn->dn, &la->meta_data.originating_change_time, "RMD_CHANGETIME");
276         if (!NT_STATUS_IS_OK(status)) {
277                 return ntstatus_to_werror(status);
278         }
279         status = dsdb_get_extended_dn_guid(dsdb_dn->dn, &la->meta_data.originating_invocation_id, "RMD_INVOCID");
280         if (!NT_STATUS_IS_OK(status)) {
281                 return ntstatus_to_werror(status);
282         }
283         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &la->meta_data.originating_usn, "RMD_ORIGINATING_USN");
284         if (!NT_STATUS_IS_OK(status)) {
285                 return ntstatus_to_werror(status);
286         }
287
288         /* we need a message_element with just one value in it */
289         v = data_blob_string_const(dsdb_dn_get_extended_linearized(*la_list, dsdb_dn, 1));
290
291         val_el.name = sa->lDAPDisplayName;
292         val_el.values = &v;
293         val_el.num_values = 1;
294
295         werr = sa->syntax->ldb_to_drsuapi(sam_ctx, schema, sa, &val_el, *la_list, &drs);
296         W_ERROR_NOT_OK_RETURN(werr);
297
298         if (drs.value_ctr.num_values != 1) {
299                 DEBUG(1,(__location__ ": Failed to build DRS blob for linked attribute %s in %s\n",
300                          sa->lDAPDisplayName, ldb_dn_get_linearized(msg->dn)));
301                 return WERR_DS_DRA_INTERNAL_ERROR;
302         }
303
304         la->value.blob = drs.value_ctr.values[0].blob;
305
306         (*la_count)++;
307         return WERR_OK;
308 }
309
310
311 /*
312   add linked attributes from an object to the list of linked
313   attributes in a getncchanges request
314  */
315 static WERROR get_nc_changes_add_links(struct ldb_context *sam_ctx,
316                                        TALLOC_CTX *mem_ctx,
317                                        struct ldb_dn *ncRoot_dn,
318                                        struct dsdb_schema *schema,
319                                        uint64_t highest_usn,
320                                        uint32_t replica_flags,
321                                        struct ldb_message *msg,
322                                        struct drsuapi_DsReplicaLinkedAttribute **la_list,
323                                        uint32_t *la_count)
324 {
325         int i;
326         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
327         uint64_t uSNChanged = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
328
329         for (i=0; i<msg->num_elements; i++) {
330                 struct ldb_message_element *el = &msg->elements[i];
331                 const struct dsdb_attribute *sa;
332                 int j;
333
334                 sa = dsdb_attribute_by_lDAPDisplayName(schema, el->name);
335
336                 if (!sa || sa->linkID == 0 || (sa->linkID & 1)) {
337                         /* we only want forward links */
338                         continue;
339                 }
340
341                 if (el->num_values && !dsdb_dn_is_upgraded_link_val(&el->values[0])) {
342                         /* its an old style link, it will have been
343                          * sent in the main replication data */
344                         continue;
345                 }
346
347                 for (j=0; j<el->num_values; j++) {
348                         struct dsdb_dn *dsdb_dn;
349                         uint64_t local_usn;
350                         NTSTATUS status;
351                         WERROR werr;
352
353                         dsdb_dn = dsdb_dn_parse(tmp_ctx, sam_ctx, &el->values[j], sa->syntax->ldap_oid);
354                         if (dsdb_dn == NULL) {
355                                 DEBUG(1,(__location__ ": Failed to parse DN for %s in %s\n",
356                                          el->name, ldb_dn_get_linearized(msg->dn)));
357                                 talloc_free(tmp_ctx);
358                                 return WERR_DS_DRA_INTERNAL_ERROR;
359                         }
360
361                         status = dsdb_get_extended_dn_uint64(dsdb_dn->dn, &local_usn, "RMD_LOCAL_USN");
362                         if (!NT_STATUS_IS_OK(status)) {
363                                 /* this can happen for attributes
364                                    given to us with old style meta
365                                    data */
366                                 continue;
367                         }
368
369                         if (local_usn > uSNChanged) {
370                                 DEBUG(1,(__location__ ": uSNChanged less than RMD_LOCAL_USN for %s on %s\n",
371                                          el->name, ldb_dn_get_linearized(msg->dn)));
372                                 talloc_free(tmp_ctx);
373                                 return WERR_DS_DRA_INTERNAL_ERROR;
374                         }
375
376                         if (local_usn < highest_usn) {
377                                 continue;
378                         }
379
380                         werr = get_nc_changes_add_la(mem_ctx, sam_ctx, schema, sa, msg,
381                                                      dsdb_dn, la_list, la_count);
382                         if (!W_ERROR_IS_OK(werr)) {
383                                 talloc_free(tmp_ctx);
384                                 return werr;
385                         }
386                 }
387         }
388
389         talloc_free(tmp_ctx);
390         return WERR_OK;
391 }
392
393 /*
394   load replUpToDateVector from a DN
395  */
396 static WERROR load_udv(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
397                        struct ldb_dn *dn, struct replUpToDateVectorBlob *ouv)
398 {
399         const char *attrs[] = { "replUpToDateVector", NULL };
400         struct ldb_result *res = NULL;
401         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
402         struct ldb_message_element *el;
403         enum ndr_err_code ndr_err;
404
405         ZERO_STRUCTP(ouv);
406
407         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
408             res->count < 1) {
409                 DEBUG(0,("load_udv: failed to read partition object\n"));
410                 talloc_free(tmp_ctx);
411                 return WERR_DS_DRA_INTERNAL_ERROR;
412         }
413
414         el = ldb_msg_find_element(res->msgs[0], "replUpToDateVector");
415         if (el == NULL || el->num_values < 1) {
416                 talloc_free(tmp_ctx);
417                 ouv->version = 2;
418                 return WERR_OK;
419         }
420
421         ndr_err = ndr_pull_struct_blob(&el->values[0], 
422                                        mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
423                                        ouv, 
424                                        (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
425         talloc_free(tmp_ctx);
426         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
427                 DEBUG(0,(__location__ ": Failed to parse replUpToDateVector for %s\n",
428                          ldb_dn_get_linearized(dn)));
429                 return WERR_DS_DRA_INTERNAL_ERROR;
430         }
431         
432         return WERR_OK;
433         
434 }
435
436 /*
437   fill in the cursors return based on the replUpToDateVector for the ncRoot_dn
438  */
439 static WERROR get_nc_changes_udv(struct ldb_context *sam_ctx,
440                                  struct ldb_dn *ncRoot_dn,
441                                  struct drsuapi_DsReplicaCursor2CtrEx *udv,
442                                  uint64_t highestUSN)
443 {
444         WERROR werr;
445         struct drsuapi_DsReplicaCursor2 *tmp_cursor;
446         NTTIME now;
447         time_t t = time(NULL);
448         struct replUpToDateVectorBlob ouv;
449         int i;
450
451         werr = load_udv(sam_ctx, udv, ncRoot_dn, &ouv);
452         if (!W_ERROR_IS_OK(werr)) {
453                 return werr;
454         }
455         
456         tmp_cursor = talloc(udv, struct drsuapi_DsReplicaCursor2);
457         tmp_cursor->source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
458         tmp_cursor->highest_usn = highestUSN;
459         unix_to_nt_time(&now, t);
460         tmp_cursor->last_sync_success = now;
461
462         udv->count = ouv.ctr.ctr2.count;
463         udv->cursors = talloc_steal(udv, ouv.ctr.ctr2.cursors);
464
465         for (i=0; i<udv->count; i++) {
466                 if (GUID_equal(&tmp_cursor->source_dsa_invocation_id,
467                                &udv->cursors[i].source_dsa_invocation_id)) {
468                         udv->cursors[i] = *tmp_cursor;
469                         break;
470                 }
471         }
472         if (i == udv->count) {
473                 udv->cursors = talloc_realloc(udv, udv->cursors, struct drsuapi_DsReplicaCursor2, udv->count+1);
474                 if (!udv->cursors) {
475                         return WERR_DS_DRA_INTERNAL_ERROR;
476                 }
477                 udv->cursors[udv->count] = *tmp_cursor;
478                 udv->count++;
479         }
480         
481         qsort(udv->cursors, udv->count,
482               sizeof(struct drsuapi_DsReplicaCursor2),
483               (comparison_fn_t)drsuapi_DsReplicaCursor2_compare);
484
485         return WERR_OK;
486 }
487
488 /*
489   sort the objects we send by tree order
490  */
491 static int site_res_cmp_parent_order(const struct ldb_message **m1, const struct ldb_message **m2)
492 {
493         return ldb_dn_compare((*m2)->dn, (*m1)->dn);
494 }
495
496 /*
497   sort the objects we send first by uSNChanged
498  */
499 static int site_res_cmp_usn_order(const struct ldb_message **m1, const struct ldb_message **m2)
500 {
501         unsigned usnchanged1, usnchanged2;
502         unsigned cn1, cn2;
503         cn1 = ldb_dn_get_comp_num((*m1)->dn);
504         cn2 = ldb_dn_get_comp_num((*m2)->dn);
505         if (cn1 != cn2) {
506                 return cn1 > cn2 ? 1 : -1;
507         }
508         usnchanged1 = ldb_msg_find_attr_as_uint(*m1, "uSNChanged", 0);
509         usnchanged2 = ldb_msg_find_attr_as_uint(*m2, "uSNChanged", 0);
510         if (usnchanged1 == usnchanged2) {
511                 return 0;
512         }
513         return usnchanged1 > usnchanged2 ? 1 : -1;
514 }
515
516
517 /* state of a partially completed getncchanges call */
518 struct drsuapi_getncchanges_state {
519         struct ldb_result *site_res;
520         uint32_t num_sent;
521         struct ldb_dn *ncRoot_dn;
522         uint64_t min_usn;
523         uint64_t highest_usn;
524         struct ldb_dn *last_dn;
525 };
526
527 /* 
528   drsuapi_DsGetNCChanges
529
530   see MS-DRSR 4.1.10.5.2 for basic logic of this function
531 */
532 WERROR dcesrv_drsuapi_DsGetNCChanges(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
533                                      struct drsuapi_DsGetNCChanges *r)
534 {
535         struct drsuapi_DsReplicaObjectIdentifier *ncRoot;
536         int ret;
537         int i;
538         struct dsdb_schema *schema;
539         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
540         struct drsuapi_DsReplicaObjectListItemEx **currentObject;
541         NTSTATUS status;
542         DATA_BLOB session_key;
543         const char *attrs[] = { "*", "distinguishedName",
544                                 "nTSecurityDescriptor",
545                                 "parentGUID",
546                                 "replPropertyMetaData",
547                                 "unicodePwd",
548                                 "dBCSPwd",
549                                 "ntPwdHistory",
550                                 "lmPwdHistory",
551                                 "supplementalCredentials",
552                                 NULL };
553         WERROR werr;
554         struct dcesrv_handle *h;
555         struct drsuapi_bind_state *b_state;     
556         struct drsuapi_getncchanges_state *getnc_state;
557         struct drsuapi_DsGetNCChangesRequest8 *req8;
558         uint32_t options;
559         uint32_t max_objects;
560
561         DCESRV_PULL_HANDLE_WERR(h, r->in.bind_handle, DRSUAPI_BIND_HANDLE);
562         b_state = h->data;
563
564         *r->out.level_out = 6;
565         /* TODO: linked attributes*/
566         r->out.ctr->ctr6.linked_attributes_count = 0;
567         r->out.ctr->ctr6.linked_attributes = NULL;
568
569         r->out.ctr->ctr6.object_count = 0;
570         r->out.ctr->ctr6.nc_object_count = 0;
571         r->out.ctr->ctr6.more_data = false;
572         r->out.ctr->ctr6.uptodateness_vector = NULL;
573
574         /* a RODC doesn't allow for any replication */
575         if (samdb_rodc(ldb_get_opaque(b_state->sam_ctx, "loadparm"))) {
576                 DEBUG(0,(__location__ ": DsGetNCChanges attempt on RODC\n"));
577                 return WERR_DS_DRA_SOURCE_DISABLED;
578         }
579
580         /* Check request revision. 
581            TODO: Adding mappings to req8 from the other levels
582          */
583         if (r->in.level != 8) {
584                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with unsupported level %u\n",
585                          r->in.level));
586                 return WERR_REVISION_MISMATCH;
587         }
588
589         req8 = &r->in.req->req8;
590
591         /* Perform access checks. */
592         /* TODO: we need to support a sync on a specific non-root
593          * DN. We'll need to find the real partition root here */
594         ncRoot = req8->naming_context;
595         if (ncRoot == NULL) {
596                 DEBUG(0,(__location__ ": Request for DsGetNCChanges with no NC\n"));
597                 return WERR_DS_DRA_INVALID_PARAMETER;
598         }
599
600         if (samdb_ntds_options(b_state->sam_ctx, &options) != LDB_SUCCESS) {
601                 return WERR_DS_DRA_INTERNAL_ERROR;
602         }
603         
604         if ((options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) &&
605             !(req8->replica_flags & DRSUAPI_DRS_SYNC_FORCED)) {
606                 return WERR_DS_DRA_SOURCE_DISABLED;
607         }
608
609
610         if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_SYNC_PACKET) {
611                 /* Ignore the _in_ uptpdateness vector*/
612                 req8->uptodateness_vector = NULL;
613         } 
614
615         werr = drs_security_level_check(dce_call, "DsGetNCChanges");
616         if (!W_ERROR_IS_OK(werr)) {
617                 return werr;
618         }
619
620         getnc_state = b_state->getncchanges_state;
621
622         /* see if a previous replication has been abandoned */
623         if (getnc_state) {
624                 struct ldb_dn *new_dn = ldb_dn_new(getnc_state, b_state->sam_ctx, ncRoot->dn);
625                 if (ldb_dn_compare(new_dn, getnc_state->ncRoot_dn) != 0) {
626                         DEBUG(0,(__location__ ": DsGetNCChanges 2nd replication on different DN %s %s (last_dn %s)\n",
627                                  ldb_dn_get_linearized(new_dn),
628                                  ldb_dn_get_linearized(getnc_state->ncRoot_dn),
629                                  ldb_dn_get_linearized(getnc_state->last_dn)));
630                         talloc_free(getnc_state);
631                         getnc_state = NULL;
632                 }
633         }
634
635         if (getnc_state == NULL) {
636                 getnc_state = talloc_zero(b_state, struct drsuapi_getncchanges_state);
637                 if (getnc_state == NULL) {
638                         return WERR_NOMEM;
639                 }
640                 b_state->getncchanges_state = getnc_state;
641                 getnc_state->ncRoot_dn = ldb_dn_new(getnc_state, b_state->sam_ctx, ncRoot->dn);
642         }
643
644         if (!ldb_dn_validate(getnc_state->ncRoot_dn) ||
645             ldb_dn_is_null(getnc_state->ncRoot_dn)) {
646                 DEBUG(0,(__location__ ": Bad DN '%s'\n", ncRoot->dn));
647                 return WERR_DS_DRA_INVALID_PARAMETER;
648         }
649
650         /* we need the session key for encrypting password attributes */
651         status = dcesrv_inherited_session_key(dce_call->conn, &session_key);
652         if (!NT_STATUS_IS_OK(status)) {
653                 DEBUG(0,(__location__ ": Failed to get session key\n"));
654                 return WERR_DS_DRA_INTERNAL_ERROR;              
655         }
656
657         /* we don't yet support extended operations */
658         if (req8->extended_op != DRSUAPI_EXOP_NONE) {
659                 DEBUG(0,(__location__ ": Request for DsGetNCChanges extended op 0x%x\n",
660                          (unsigned)req8->extended_op));
661                 return WERR_DS_DRA_NOT_SUPPORTED;
662         }
663
664         /* 
665            TODO: MS-DRSR section 4.1.10.1.1
666            Work out if this is the start of a new cycle */
667
668         if (getnc_state->site_res == NULL) {
669                 char* search_filter;
670                 enum ldb_scope scope = LDB_SCOPE_SUBTREE;
671                 const char *extra_filter;
672
673                 extra_filter = lp_parm_string(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "object filter");
674
675                 getnc_state->min_usn = req8->highwatermark.highest_usn;
676
677                 /* Construct response. */
678                 search_filter = talloc_asprintf(mem_ctx,
679                                                 "(uSNChanged>=%llu)",
680                                                 (unsigned long long)(getnc_state->min_usn+1));
681         
682                 if (extra_filter) {
683                         search_filter = talloc_asprintf(mem_ctx, "(&%s(%s))", search_filter, extra_filter);
684                 }
685
686                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_CRITICAL_ONLY) {
687                         search_filter = talloc_asprintf(mem_ctx,
688                                                         "(&%s(isCriticalSystemObject=TRUE))",
689                                                         search_filter);
690                 }
691                 
692                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_ASYNC_REP) {
693                         scope = LDB_SCOPE_BASE;
694                 }
695                 
696                 DEBUG(1,(__location__ ": getncchanges on %s using filter %s\n",
697                          ldb_dn_get_linearized(getnc_state->ncRoot_dn), search_filter));
698                 ret = drsuapi_search_with_extended_dn(b_state->sam_ctx, getnc_state, &getnc_state->site_res,
699                                                       getnc_state->ncRoot_dn, scope, attrs,
700                                                       search_filter);
701                 if (ret != LDB_SUCCESS) {
702                         return WERR_DS_DRA_INTERNAL_ERROR;
703                 }
704
705                 if (req8->replica_flags & DRSUAPI_DS_REPLICA_NEIGHBOUR_RETURN_OBJECT_PARENTS) {
706                         qsort(getnc_state->site_res->msgs,
707                               getnc_state->site_res->count,
708                               sizeof(getnc_state->site_res->msgs[0]),
709                               (comparison_fn_t)site_res_cmp_parent_order);
710                 } else {
711                         qsort(getnc_state->site_res->msgs,
712                               getnc_state->site_res->count,
713                               sizeof(getnc_state->site_res->msgs[0]),
714                               (comparison_fn_t)site_res_cmp_usn_order);
715                 }
716
717         }
718
719         /* Prefix mapping */
720         schema = dsdb_get_schema(b_state->sam_ctx);
721         if (!schema) {
722                 DEBUG(0,("No schema in sam_ctx\n"));
723                 return WERR_DS_DRA_INTERNAL_ERROR;
724         }
725
726         r->out.ctr->ctr6.naming_context = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
727         *r->out.ctr->ctr6.naming_context = *ncRoot;
728
729         if (dsdb_find_guid_by_dn(b_state->sam_ctx, getnc_state->ncRoot_dn, 
730                                  &r->out.ctr->ctr6.naming_context->guid) != LDB_SUCCESS) {
731                 DEBUG(0,(__location__ ": Failed to find GUID of ncRoot_dn %s\n",
732                          ldb_dn_get_linearized(getnc_state->ncRoot_dn)));
733                 return WERR_DS_DRA_INTERNAL_ERROR;
734         }
735
736         /* find the SID if there is one */
737         dsdb_find_sid_by_dn(b_state->sam_ctx, getnc_state->ncRoot_dn, &r->out.ctr->ctr6.naming_context->sid);
738
739         dsdb_get_oid_mappings_drsuapi(schema, true, mem_ctx, &ctr);
740         r->out.ctr->ctr6.mapping_ctr = *ctr;
741
742         r->out.ctr->ctr6.source_dsa_guid = *(samdb_ntds_objectGUID(b_state->sam_ctx));
743         r->out.ctr->ctr6.source_dsa_invocation_id = *(samdb_ntds_invocation_id(b_state->sam_ctx));
744
745         r->out.ctr->ctr6.old_highwatermark = req8->highwatermark;
746         r->out.ctr->ctr6.new_highwatermark = req8->highwatermark;
747
748         r->out.ctr->ctr6.first_object = NULL;
749         currentObject = &r->out.ctr->ctr6.first_object;
750
751         /* use this to force single objects at a time, which is useful
752          * for working out what object is giving problems
753          */
754         max_objects = lp_parm_int(dce_call->conn->dce_ctx->lp_ctx, NULL, "drs", "max object sync", 1000);
755         if (req8->max_object_count < max_objects) {
756                 max_objects = req8->max_object_count;
757         }
758
759         for(i=getnc_state->num_sent; 
760             i<getnc_state->site_res->count && 
761                     (r->out.ctr->ctr6.object_count < max_objects);
762             i++) {
763                 int uSN;
764                 struct drsuapi_DsReplicaObjectListItemEx *obj;
765                 struct ldb_message *msg = getnc_state->site_res->msgs[i];
766
767                 obj = talloc_zero(mem_ctx, struct drsuapi_DsReplicaObjectListItemEx);
768
769                 uSN = ldb_msg_find_attr_as_int(msg, "uSNChanged", -1);
770                 if (uSN > r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn) {
771                         r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn = uSN;
772                 }
773                 if (uSN > getnc_state->highest_usn) {
774                         getnc_state->highest_usn = uSN;
775                 }
776
777                 werr = get_nc_changes_build_object(obj, msg,
778                                                    b_state->sam_ctx, getnc_state->ncRoot_dn, 
779                                                    schema, &session_key, getnc_state->min_usn,
780                                                    req8->replica_flags);
781                 if (!W_ERROR_IS_OK(werr)) {
782                         return werr;
783                 }
784
785                 werr = get_nc_changes_add_links(b_state->sam_ctx, mem_ctx,
786                                                 getnc_state->ncRoot_dn,
787                                                 schema, getnc_state->min_usn,
788                                                 req8->replica_flags,
789                                                 msg,
790                                                 &r->out.ctr->ctr6.linked_attributes,
791                                                 &r->out.ctr->ctr6.linked_attributes_count);
792                 if (!W_ERROR_IS_OK(werr)) {
793                         return werr;
794                 }
795
796                 if (obj->meta_data_ctr == NULL) {
797                         DEBUG(0,(__location__ ": getncchanges skipping send of object %s\n",
798                                  ldb_dn_get_linearized(msg->dn)));
799                         /* no attributes to send */
800                         talloc_free(obj);
801                         continue;
802                 }
803
804                 r->out.ctr->ctr6.object_count++;
805                 
806                 *currentObject = obj;
807                 currentObject = &obj->next_object;
808
809                 talloc_free(getnc_state->last_dn);
810                 getnc_state->last_dn = ldb_dn_copy(getnc_state, msg->dn);
811
812                 DEBUG(8,(__location__ ": replicating object %s\n", ldb_dn_get_linearized(msg->dn)));
813         }
814
815         getnc_state->num_sent += r->out.ctr->ctr6.object_count;
816
817         r->out.ctr->ctr6.nc_object_count = getnc_state->site_res->count;
818
819         /* the client can us to call UpdateRefs on its behalf to
820            re-establish monitoring of the NC */
821         if ((req8->replica_flags & DRSUAPI_DRS_ADD_REF) && 
822             !GUID_all_zero(&req8->destination_dsa_guid)) {
823                 struct drsuapi_DsReplicaUpdateRefsRequest1 ureq;
824                 ureq.naming_context = ncRoot;
825                 ureq.dest_dsa_dns_name = talloc_asprintf(mem_ctx, "%s._msdcs.%s",
826                                                          GUID_string(mem_ctx, &req8->destination_dsa_guid),
827                                                          lp_realm(dce_call->conn->dce_ctx->lp_ctx));
828                 if (!ureq.dest_dsa_dns_name) {
829                         return WERR_NOMEM;
830                 }
831                 ureq.dest_dsa_guid = req8->destination_dsa_guid;
832                 ureq.options = DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE |
833                         DRSUAPI_DS_REPLICA_UPDATE_ASYNCHRONOUS_OPERATION |
834                         DRSUAPI_DS_REPLICA_UPDATE_GETCHG_CHECK;
835                 werr = drsuapi_UpdateRefs(b_state, mem_ctx, &ureq);
836                 if (!W_ERROR_IS_OK(werr)) {
837                         DEBUG(0,(__location__ ": Failed UpdateRefs in DsGetNCChanges - %s\n",
838                                  win_errstr(werr)));
839                 }
840         }
841
842         if (i < getnc_state->site_res->count) {
843                 r->out.ctr->ctr6.more_data = true;
844         } else {
845                 r->out.ctr->ctr6.uptodateness_vector = talloc(mem_ctx, struct drsuapi_DsReplicaCursor2CtrEx);
846                 r->out.ctr->ctr6.uptodateness_vector->version = 2;
847                 r->out.ctr->ctr6.uptodateness_vector->reserved1 = 0;
848                 r->out.ctr->ctr6.uptodateness_vector->reserved2 = 0;
849
850                 r->out.ctr->ctr6.new_highwatermark.highest_usn = r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn;
851
852                 werr = get_nc_changes_udv(b_state->sam_ctx, getnc_state->ncRoot_dn, 
853                                           r->out.ctr->ctr6.uptodateness_vector,
854                                           getnc_state->highest_usn);
855                 if (!W_ERROR_IS_OK(werr)) {
856                         return werr;
857                 }
858
859                 talloc_free(getnc_state);
860                 b_state->getncchanges_state = NULL;
861         }
862
863         DEBUG(r->out.ctr->ctr6.more_data?2:1,
864               ("DsGetNCChanges with uSNChanged >= %llu flags 0x%08x on %s gave %u objects (done %d/%d la=%d)\n",
865                (unsigned long long)(req8->highwatermark.highest_usn+1),
866                req8->replica_flags,
867                ncRoot->dn, r->out.ctr->ctr6.object_count,
868                i, r->out.ctr->ctr6.more_data?getnc_state->site_res->count:i,
869                r->out.ctr->ctr6.linked_attributes_count));
870
871 #if 0
872         if (!r->out.ctr->ctr6.more_data) {
873                 NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsGetNCChanges, NDR_BOTH, r);
874         }
875 #endif
876
877         return WERR_OK;
878 }