s4-repl: Let dsdb_replicated_objects_convert() to accept schema from caller
[metze/samba/wip.git] / source4 / dsdb / repl / replicated_objects.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    Helper functions for applying replicated objects
4    
5    Copyright (C) Stefan Metzmacher <metze@samba.org> 2007
6     
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19    
20 */
21
22 #include "includes.h"
23 #include "dsdb/samdb/samdb.h"
24 #include "lib/ldb/include/ldb_errors.h"
25 #include "../lib/util/dlinklist.h"
26 #include "librpc/gen_ndr/ndr_misc.h"
27 #include "librpc/gen_ndr/ndr_drsuapi.h"
28 #include "librpc/gen_ndr/ndr_drsblobs.h"
29 #include "../lib/crypto/crypto.h"
30 #include "../libcli/drsuapi/drsuapi.h"
31 #include "libcli/auth/libcli_auth.h"
32 #include "param/param.h"
33
34 WERROR dsdb_convert_object_ex(struct ldb_context *ldb,
35                               const struct dsdb_schema *schema,
36                               const struct dsdb_schema_prefixmap *pfm_remote,
37                               const struct drsuapi_DsReplicaObjectListItemEx *in,
38                               const DATA_BLOB *gensec_skey,
39                               TALLOC_CTX *mem_ctx,
40                               struct dsdb_extended_replicated_object *out)
41 {
42         NTSTATUS nt_status;
43         WERROR status;
44         uint32_t i;
45         struct ldb_message *msg;
46         struct replPropertyMetaDataBlob *md;
47         struct ldb_val guid_value;
48         NTTIME whenChanged = 0;
49         time_t whenChanged_t;
50         const char *whenChanged_s;
51         const char *rdn_name = NULL;
52         const struct ldb_val *rdn_value = NULL;
53         const struct dsdb_attribute *rdn_attr = NULL;
54         uint32_t rdn_attid;
55         struct drsuapi_DsReplicaAttribute *name_a = NULL;
56         struct drsuapi_DsReplicaMetaData *name_d = NULL;
57         struct replPropertyMetaData1 *rdn_m = NULL;
58         struct dom_sid *sid = NULL;
59         uint32_t rid = 0;
60         int ret;
61
62         if (!in->object.identifier) {
63                 return WERR_FOOBAR;
64         }
65
66         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
67                 return WERR_FOOBAR;
68         }
69
70         if (in->object.attribute_ctr.num_attributes != 0 && !in->meta_data_ctr) {
71                 return WERR_FOOBAR;
72         }
73
74         if (in->object.attribute_ctr.num_attributes != in->meta_data_ctr->count) {
75                 return WERR_FOOBAR;
76         }
77
78         sid = &in->object.identifier->sid;
79         if (sid->num_auths > 0) {
80                 rid = sid->sub_auths[sid->num_auths - 1];
81         }
82
83         msg = ldb_msg_new(mem_ctx);
84         W_ERROR_HAVE_NO_MEMORY(msg);
85
86         msg->dn                 = ldb_dn_new(msg, ldb, in->object.identifier->dn);
87         W_ERROR_HAVE_NO_MEMORY(msg->dn);
88
89         rdn_name        = ldb_dn_get_rdn_name(msg->dn);
90         rdn_attr        = dsdb_attribute_by_lDAPDisplayName(schema, rdn_name);
91         if (!rdn_attr) {
92                 return WERR_FOOBAR;
93         }
94         rdn_attid       = rdn_attr->attributeID_id;
95         rdn_value       = ldb_dn_get_rdn_val(msg->dn);
96
97         msg->num_elements       = in->object.attribute_ctr.num_attributes;
98         msg->elements           = talloc_array(msg, struct ldb_message_element,
99                                                msg->num_elements);
100         W_ERROR_HAVE_NO_MEMORY(msg->elements);
101
102         md = talloc(mem_ctx, struct replPropertyMetaDataBlob);
103         W_ERROR_HAVE_NO_MEMORY(md);
104
105         md->version             = 1;
106         md->reserved            = 0;
107         md->ctr.ctr1.count      = in->meta_data_ctr->count;
108         md->ctr.ctr1.reserved   = 0;
109         md->ctr.ctr1.array      = talloc_array(mem_ctx,
110                                                struct replPropertyMetaData1,
111                                                md->ctr.ctr1.count + 1); /* +1 because of the RDN attribute */
112         W_ERROR_HAVE_NO_MEMORY(md->ctr.ctr1.array);
113
114         for (i=0; i < in->meta_data_ctr->count; i++) {
115                 struct drsuapi_DsReplicaAttribute *a;
116                 struct drsuapi_DsReplicaMetaData *d;
117                 struct replPropertyMetaData1 *m;
118                 struct ldb_message_element *e;
119                 uint32_t j;
120
121                 a = &in->object.attribute_ctr.attributes[i];
122                 d = &in->meta_data_ctr->meta_data[i];
123                 m = &md->ctr.ctr1.array[i];
124                 e = &msg->elements[i];
125
126                 for (j=0; j<a->value_ctr.num_values; j++) {
127                         status = drsuapi_decrypt_attribute(a->value_ctr.values[j].blob, gensec_skey, rid, a);
128                         W_ERROR_NOT_OK_RETURN(status);
129                 }
130
131                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, pfm_remote,
132                                                        a, msg->elements, e);
133                 W_ERROR_NOT_OK_RETURN(status);
134
135                 m->attid                        = a->attid;
136                 m->version                      = d->version;
137                 m->originating_change_time      = d->originating_change_time;
138                 m->originating_invocation_id    = d->originating_invocation_id;
139                 m->originating_usn              = d->originating_usn;
140                 m->local_usn                    = 0;
141
142                 if (d->originating_change_time > whenChanged) {
143                         whenChanged = d->originating_change_time;
144                 }
145
146                 if (a->attid == DRSUAPI_ATTID_name) {
147                         name_a = a;
148                         name_d = d;
149                         rdn_m = &md->ctr.ctr1.array[md->ctr.ctr1.count];
150                 }
151         }
152
153         if (rdn_m) {
154                 struct ldb_message_element *el;
155                 el = ldb_msg_find_element(msg, rdn_attr->lDAPDisplayName);
156                 if (!el) {
157                         ret = ldb_msg_add_value(msg, rdn_attr->lDAPDisplayName, rdn_value, NULL);
158                         if (ret != LDB_SUCCESS) {
159                                 return WERR_FOOBAR;
160                         }
161                 } else {
162                         if (el->num_values != 1) {
163                                 DEBUG(0,(__location__ ": Unexpected num_values=%u\n",
164                                          el->num_values));
165                                 return WERR_FOOBAR;                             
166                         }
167                         if (!ldb_val_equal_exact(&el->values[0], rdn_value)) {
168                                 DEBUG(0,(__location__ ": RDN value changed? '%*.*s' '%*.*s'\n",
169                                          (int)el->values[0].length, (int)el->values[0].length, el->values[0].data,
170                                          (int)rdn_value->length, (int)rdn_value->length, rdn_value->data));
171                                 return WERR_FOOBAR;                             
172                         }
173                 }
174
175                 rdn_m->attid                            = rdn_attid;
176                 rdn_m->version                          = name_d->version;
177                 rdn_m->originating_change_time          = name_d->originating_change_time;
178                 rdn_m->originating_invocation_id        = name_d->originating_invocation_id;
179                 rdn_m->originating_usn                  = name_d->originating_usn;
180                 rdn_m->local_usn                        = 0;
181                 md->ctr.ctr1.count++;
182
183         }
184
185         whenChanged_t = nt_time_to_unix(whenChanged);
186         whenChanged_s = ldb_timestring(msg, whenChanged_t);
187         W_ERROR_HAVE_NO_MEMORY(whenChanged_s);
188
189         nt_status = GUID_to_ndr_blob(&in->object.identifier->guid, msg, &guid_value);
190         if (!NT_STATUS_IS_OK(nt_status)) {
191                 return ntstatus_to_werror(nt_status);
192         }
193
194         out->msg                = msg;
195         out->guid_value         = guid_value;
196         out->when_changed       = whenChanged_s;
197         out->meta_data          = md;
198         return WERR_OK;
199 }
200
201 WERROR dsdb_replicated_objects_convert(struct ldb_context *ldb,
202                                        const struct dsdb_schema *schema,
203                                        const char *partition_dn_str,
204                                        const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr,
205                                        uint32_t object_count,
206                                        const struct drsuapi_DsReplicaObjectListItemEx *first_object,
207                                        uint32_t linked_attributes_count,
208                                        const struct drsuapi_DsReplicaLinkedAttribute *linked_attributes,
209                                        const struct repsFromTo1 *source_dsa,
210                                        const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector,
211                                        const DATA_BLOB *gensec_skey,
212                                        TALLOC_CTX *mem_ctx,
213                                        struct dsdb_extended_replicated_objects **objects)
214 {
215         WERROR status;
216         struct ldb_dn *partition_dn;
217         struct dsdb_schema_prefixmap *pfm_remote;
218         struct dsdb_extended_replicated_objects *out;
219         const struct drsuapi_DsReplicaObjectListItemEx *cur;
220         uint32_t i;
221
222         out = talloc_zero(mem_ctx, struct dsdb_extended_replicated_objects);
223         W_ERROR_HAVE_NO_MEMORY(out);
224         out->version            = DSDB_EXTENDED_REPLICATED_OBJECTS_VERSION;
225
226         /*
227          * Ensure schema is kept valid for as long as 'out'
228          * which may contain pointers to it
229          */
230         talloc_reference(out, schema);
231
232         partition_dn = ldb_dn_new(out, ldb, partition_dn_str);
233         W_ERROR_HAVE_NO_MEMORY_AND_FREE(partition_dn, out);
234
235         status = dsdb_schema_pfm_from_drsuapi_pfm(mapping_ctr, true,
236                                                   out, &pfm_remote, NULL);
237         if (!W_ERROR_IS_OK(status)) {
238                 DEBUG(0,(__location__ ": Failed to decode remote prefixMap: %s",
239                          win_errstr(status)));
240                 talloc_free(out);
241                 return status;
242         }
243
244         if (ldb_dn_compare(partition_dn, ldb_get_schema_basedn(ldb)) != 0) {
245                 /*
246                  * check for schema changes in case
247                  * we are not replicating Schema NC
248                  */
249                 status = dsdb_schema_info_cmp(schema, mapping_ctr);
250                 if (!W_ERROR_IS_OK(status)) {
251                         DEBUG(1,("Remote schema has changed while replicating %s\n",
252                                  partition_dn_str));
253                         talloc_free(out);
254                         return status;
255                 }
256         }
257
258         out->partition_dn       = partition_dn;
259
260         out->source_dsa         = source_dsa;
261         out->uptodateness_vector= uptodateness_vector;
262
263         out->num_objects        = object_count;
264         out->objects            = talloc_array(out,
265                                                struct dsdb_extended_replicated_object,
266                                                out->num_objects);
267         W_ERROR_HAVE_NO_MEMORY_AND_FREE(out->objects, out);
268
269         /* pass the linked attributes down to the repl_meta_data
270            module */
271         out->linked_attributes_count = linked_attributes_count;
272         out->linked_attributes       = linked_attributes;
273
274         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
275                 if (i == out->num_objects) {
276                         talloc_free(out);
277                         return WERR_FOOBAR;
278                 }
279
280                 status = dsdb_convert_object_ex(ldb, schema, pfm_remote,
281                                                 cur, gensec_skey,
282                                                 out->objects, &out->objects[i]);
283                 if (!W_ERROR_IS_OK(status)) {
284                         talloc_free(out);
285                         DEBUG(0,("Failed to convert object %s: %s\n",
286                                  cur->object.identifier->dn,
287                                  win_errstr(status)));
288                         return status;
289                 }
290         }
291         if (i != out->num_objects) {
292                 talloc_free(out);
293                 return WERR_FOOBAR;
294         }
295
296         /* free pfm_remote, we won't need it anymore */
297         talloc_free(pfm_remote);
298
299         *objects = out;
300         return WERR_OK;
301 }
302
303 WERROR dsdb_replicated_objects_commit(struct ldb_context *ldb,
304                                       struct dsdb_extended_replicated_objects *objects,
305                                       uint64_t *notify_uSN)
306 {
307         struct ldb_result *ext_res;
308         int ret;
309         uint64_t seq_num1, seq_num2;
310
311         /* TODO: handle linked attributes */
312
313         /* wrap the extended operation in a transaction 
314            See [MS-DRSR] 3.3.2 Transactions
315          */
316         ret = ldb_transaction_start(ldb);
317         if (ret != LDB_SUCCESS) {
318                 DEBUG(0,(__location__ " Failed to start transaction\n"));
319                 return WERR_FOOBAR;
320         }
321
322         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num1, NULL);
323         if (ret != LDB_SUCCESS) {
324                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
325                 ldb_transaction_cancel(ldb);
326                 return WERR_FOOBAR;             
327         }
328
329         ret = ldb_extended(ldb, DSDB_EXTENDED_REPLICATED_OBJECTS_OID, objects, &ext_res);
330         if (ret != LDB_SUCCESS) {
331                 DEBUG(0,("Failed to apply records: %s: %s\n",
332                          ldb_errstring(ldb), ldb_strerror(ret)));
333                 ldb_transaction_cancel(ldb);
334                 return WERR_FOOBAR;
335         }
336         talloc_free(ext_res);
337
338         ret = ldb_transaction_prepare_commit(ldb);
339         if (ret != LDB_SUCCESS) {
340                 DEBUG(0,(__location__ " Failed to prepare commit of transaction: %s\n",
341                          ldb_errstring(ldb)));
342                 return WERR_FOOBAR;
343         }
344
345         ret = dsdb_load_partition_usn(ldb, objects->partition_dn, &seq_num2, NULL);
346         if (ret != LDB_SUCCESS) {
347                 DEBUG(0,(__location__ " Failed to load partition uSN\n"));
348                 ldb_transaction_cancel(ldb);
349                 return WERR_FOOBAR;             
350         }
351
352         /* if this replication partner didn't need to be notified
353            before this transaction then it still doesn't need to be
354            notified, as the changes came from this server */    
355         if (seq_num2 > seq_num1 && seq_num1 <= *notify_uSN) {
356                 *notify_uSN = seq_num2;
357         }
358
359         ret = ldb_transaction_commit(ldb);
360         if (ret != LDB_SUCCESS) {
361                 DEBUG(0,(__location__ " Failed to commit transaction\n"));
362                 return WERR_FOOBAR;
363         }
364
365
366         DEBUG(2,("Replicated %u objects (%u linked attributes) for %s\n",
367                  objects->num_objects, objects->linked_attributes_count,
368                  ldb_dn_get_linearized(objects->partition_dn)));
369                  
370         return WERR_OK;
371 }
372
373 static WERROR dsdb_origin_object_convert(struct ldb_context *ldb,
374                                          const struct dsdb_schema *schema,
375                                          const struct drsuapi_DsReplicaObjectListItem *in,
376                                          TALLOC_CTX *mem_ctx,
377                                          struct ldb_message **_msg)
378 {
379         WERROR status;
380         unsigned int i;
381         struct ldb_message *msg;
382
383         if (!in->object.identifier) {
384                 return WERR_FOOBAR;
385         }
386
387         if (!in->object.identifier->dn || !in->object.identifier->dn[0]) {
388                 return WERR_FOOBAR;
389         }
390
391         msg = ldb_msg_new(mem_ctx);
392         W_ERROR_HAVE_NO_MEMORY(msg);
393
394         msg->dn = ldb_dn_new(msg, ldb, in->object.identifier->dn);
395         W_ERROR_HAVE_NO_MEMORY(msg->dn);
396
397         msg->num_elements       = in->object.attribute_ctr.num_attributes;
398         msg->elements           = talloc_array(msg, struct ldb_message_element,
399                                                msg->num_elements);
400         W_ERROR_HAVE_NO_MEMORY(msg->elements);
401
402         for (i=0; i < msg->num_elements; i++) {
403                 struct drsuapi_DsReplicaAttribute *a;
404                 struct ldb_message_element *e;
405
406                 a = &in->object.attribute_ctr.attributes[i];
407                 e = &msg->elements[i];
408
409                 status = dsdb_attribute_drsuapi_to_ldb(ldb, schema, schema->prefixmap,
410                                                        a, msg->elements, e);
411                 W_ERROR_NOT_OK_RETURN(status);
412         }
413
414
415         *_msg = msg;
416
417         return WERR_OK;
418 }
419
420 WERROR dsdb_origin_objects_commit(struct ldb_context *ldb,
421                                   TALLOC_CTX *mem_ctx,
422                                   const struct drsuapi_DsReplicaObjectListItem *first_object,
423                                   uint32_t *_num,
424                                   struct drsuapi_DsReplicaObjectIdentifier2 **_ids)
425 {
426         WERROR status;
427         const struct dsdb_schema *schema;
428         const struct drsuapi_DsReplicaObjectListItem *cur;
429         struct ldb_message **objects;
430         struct drsuapi_DsReplicaObjectIdentifier2 *ids;
431         uint32_t i;
432         uint32_t num_objects = 0;
433         const char * const attrs[] = {
434                 "objectGUID",
435                 "objectSid",
436                 NULL
437         };
438         struct ldb_result *res;
439         int ret;
440
441         for (cur = first_object; cur; cur = cur->next_object) {
442                 num_objects++;
443         }
444
445         if (num_objects == 0) {
446                 return WERR_OK;
447         }
448
449         ret = ldb_transaction_start(ldb);
450         if (ret != LDB_SUCCESS) {
451                 return WERR_DS_INTERNAL_FAILURE;
452         }
453
454         objects = talloc_array(mem_ctx, struct ldb_message *,
455                                num_objects);
456         if (objects == NULL) {
457                 status = WERR_NOMEM;
458                 goto cancel;
459         }
460
461         schema = dsdb_get_schema(ldb, objects);
462         if (!schema) {
463                 return WERR_DS_SCHEMA_NOT_LOADED;
464         }
465
466         for (i=0, cur = first_object; cur; cur = cur->next_object, i++) {
467                 status = dsdb_origin_object_convert(ldb, schema, cur,
468                                                     objects, &objects[i]);
469                 if (!W_ERROR_IS_OK(status)) {
470                         goto cancel;
471                 }
472         }
473
474         ids = talloc_array(mem_ctx,
475                            struct drsuapi_DsReplicaObjectIdentifier2,
476                            num_objects);
477         if (ids == NULL) {
478                 status = WERR_NOMEM;
479                 goto cancel;
480         }
481
482         for (i=0; i < num_objects; i++) {
483                 struct dom_sid *sid = NULL;
484                 struct ldb_request *add_req;
485
486                 DEBUG(6,(__location__ ": adding %s\n", 
487                          ldb_dn_get_linearized(objects[i]->dn)));
488
489                 ret = ldb_build_add_req(&add_req,
490                                         ldb,
491                                         objects,
492                                         objects[i],
493                                         NULL,
494                                         NULL,
495                                         ldb_op_default_callback,
496                                         NULL);
497                 if (ret != LDB_SUCCESS) {
498                         status = WERR_DS_INTERNAL_FAILURE;
499                         goto cancel;
500                 }
501
502                 ret = ldb_request_add_control(add_req, LDB_CONTROL_RELAX_OID, true, NULL);
503                 if (ret != LDB_SUCCESS) {
504                         status = WERR_DS_INTERNAL_FAILURE;
505                         goto cancel;
506                 }
507                 
508                 ret = ldb_request(ldb, add_req);
509                 if (ret == LDB_SUCCESS) {
510                         ret = ldb_wait(add_req->handle, LDB_WAIT_ALL);
511                 }
512                 if (ret != LDB_SUCCESS) {
513                         DEBUG(0,(__location__ ": Failed add of %s - %s\n",
514                                  ldb_dn_get_linearized(objects[i]->dn), ldb_errstring(ldb)));
515                         status = WERR_DS_INTERNAL_FAILURE;
516                         goto cancel;
517                 }
518
519                 talloc_free(add_req);
520
521                 ret = ldb_search(ldb, objects, &res, objects[i]->dn,
522                                  LDB_SCOPE_BASE, attrs,
523                                  "(objectClass=*)");
524                 if (ret != LDB_SUCCESS) {
525                         status = WERR_DS_INTERNAL_FAILURE;
526                         goto cancel;
527                 }
528                 ids[i].guid = samdb_result_guid(res->msgs[0], "objectGUID");
529                 sid = samdb_result_dom_sid(objects, res->msgs[0], "objectSid");
530                 if (sid) {
531                         ids[i].sid = *sid;
532                 } else {
533                         ZERO_STRUCT(ids[i].sid);
534                 }
535         }
536
537         ret = ldb_transaction_commit(ldb);
538         if (ret != LDB_SUCCESS) {
539                 return WERR_DS_INTERNAL_FAILURE;
540         }
541
542         talloc_free(objects);
543
544         *_num = num_objects;
545         *_ids = ids;
546         return WERR_OK;
547
548 cancel:
549         talloc_free(objects);
550         ldb_transaction_cancel(ldb);
551         return status;
552 }