fa2b0679dfb82e9d3f426d1eaa289dab9d79cb76
[kai/samba.git] / source4 / dsdb / kcc / kcc_periodic.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    KCC service periodic handling
4    
5    Copyright (C) Andrew Tridgell 2009
6    based on repl service code
7     
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20    
21 */
22
23 #include "includes.h"
24 #include "lib/events/events.h"
25 #include "dsdb/samdb/samdb.h"
26 #include "auth/auth.h"
27 #include "smbd/service.h"
28 #include "lib/messaging/irpc.h"
29 #include "dsdb/kcc/kcc_connection.h"
30 #include "dsdb/kcc/kcc_service.h"
31 #include "lib/ldb/include/ldb_errors.h"
32 #include "../lib/util/dlinklist.h"
33 #include "librpc/gen_ndr/ndr_misc.h"
34 #include "librpc/gen_ndr/ndr_drsuapi.h"
35 #include "librpc/gen_ndr/ndr_drsblobs.h"
36 #include "librpc/gen_ndr/ndr_irpc_c.h"
37 #include "param/param.h"
38
39 /*
40  * see if two repsFromToBlob blobs are for the same source DSA
41  */
42 static bool kccsrv_same_source_dsa(struct repsFromToBlob *r1, struct repsFromToBlob *r2)
43 {
44         return GUID_compare(&r1->ctr.ctr1.source_dsa_obj_guid,
45                             &r2->ctr.ctr1.source_dsa_obj_guid) == 0;
46 }
47
48 /*
49  * see if a repsFromToBlob is in a list
50  */
51 static bool reps_in_list(struct repsFromToBlob *r, struct repsFromToBlob *reps, uint32_t count)
52 {
53         uint32_t i;
54         for (i=0; i<count; i++) {
55                 if (kccsrv_same_source_dsa(r, &reps[i])) {
56                         return true;
57                 }
58         }
59         return false;
60 }
61
62 /*
63   make sure we only add repsFrom entries for DCs who are masters for
64   the partition
65  */
66 static bool check_MasterNC(struct kccsrv_partition *p, struct repsFromToBlob *r,
67                            struct ldb_result *res)
68 {
69         struct repsFromTo1 *r1 = &r->ctr.ctr1;
70         struct GUID invocation_id = r1->source_dsa_invocation_id;
71         unsigned int i, j;
72
73         /* we are expecting only version 1 */
74         SMB_ASSERT(r->version == 1);
75
76         for (i=0; i<res->count; i++) {
77                 struct ldb_message *msg = res->msgs[i];
78                 struct ldb_message_element *el;
79                 struct ldb_dn *dn;
80
81                 struct GUID id2 = samdb_result_guid(msg, "invocationID");
82                 if (GUID_all_zero(&id2) ||
83                     !GUID_equal(&invocation_id, &id2)) {
84                         continue;
85                 }
86
87                 el = ldb_msg_find_element(msg, "msDS-hasMasterNCs");
88                 if (!el || el->num_values == 0) {
89                         el = ldb_msg_find_element(msg, "hasMasterNCs");
90                         if (!el || el->num_values == 0) {
91                                 continue;
92                         }
93                 }
94                 for (j=0; j<el->num_values; j++) {
95                         dn = ldb_dn_from_ldb_val(p, p->service->samdb, &el->values[j]);
96                         if (!ldb_dn_validate(dn)) {
97                                 talloc_free(dn);
98                                 continue;
99                         }
100                         if (ldb_dn_compare(dn, p->dn) == 0) {
101                                 talloc_free(dn);
102                                 DEBUG(5,("%s %s match on %s in %s\n",
103                                          r1->other_info->dns_name,
104                                          el->name,
105                                          ldb_dn_get_linearized(dn),
106                                          ldb_dn_get_linearized(msg->dn)));
107                                 return true;
108                         }
109                         talloc_free(dn);
110                 }
111         }
112         return false;
113 }
114
115 struct kccsrv_notify_drepl_server_state {
116         struct dreplsrv_refresh r;
117 };
118
119 static void kccsrv_notify_drepl_server_done(struct tevent_req *subreq);
120
121 /**
122  * Force dreplsrv to update its state as topology is changed
123  */
124 static void kccsrv_notify_drepl_server(struct kccsrv_service *s,
125                                        TALLOC_CTX *mem_ctx)
126 {
127         struct kccsrv_notify_drepl_server_state *state;
128         struct dcerpc_binding_handle *irpc_handle;
129         struct tevent_req *subreq;
130
131         state = talloc_zero(s, struct kccsrv_notify_drepl_server_state);
132         if (state == NULL) {
133                 return;
134         }
135
136         irpc_handle = irpc_binding_handle_by_name(state, s->task->msg_ctx,
137                                                   "dreplsrv", &ndr_table_irpc);
138         if (irpc_handle == NULL) {
139                 /* dreplsrv is not running yet */
140                 TALLOC_FREE(state);
141                 return;
142         }
143
144         subreq = dcerpc_dreplsrv_refresh_r_send(state, s->task->event_ctx,
145                                                 irpc_handle, &state->r);
146         if (subreq == NULL) {
147                 TALLOC_FREE(state);
148                 return;
149         }
150         tevent_req_set_callback(subreq, kccsrv_notify_drepl_server_done, state);
151 }
152
153 static void kccsrv_notify_drepl_server_done(struct tevent_req *subreq)
154 {
155         struct kccsrv_notify_drepl_server_state *state =
156                 tevent_req_callback_data(subreq,
157                 struct kccsrv_notify_drepl_server_state);
158         NTSTATUS status;
159
160         status = dcerpc_dreplsrv_refresh_r_recv(subreq, state);
161         TALLOC_FREE(subreq);
162
163         /* we don't care about errors */
164         TALLOC_FREE(state);
165 }
166
167 static uint32_t kccsrv_replica_flags(struct kccsrv_service *s)
168 {
169         if (s->am_rodc) {
170                 return DRSUAPI_DRS_INIT_SYNC |
171                         DRSUAPI_DRS_PER_SYNC |
172                         DRSUAPI_DRS_ADD_REF |
173                         DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
174                         DRSUAPI_DRS_NONGC_RO_REP;
175         }
176         return DRSUAPI_DRS_INIT_SYNC |
177                 DRSUAPI_DRS_PER_SYNC |
178                 DRSUAPI_DRS_ADD_REF |
179                 DRSUAPI_DRS_WRIT_REP;
180 }
181
182 /*
183  * add any missing repsFrom structures to our partitions
184  */
185 static NTSTATUS kccsrv_add_repsFrom(struct kccsrv_service *s, TALLOC_CTX *mem_ctx,
186                                     struct repsFromToBlob *reps, uint32_t count,
187                                     struct ldb_result *res)
188 {
189         struct kccsrv_partition *p;
190         bool notify_dreplsrv = false;
191         uint32_t replica_flags = kccsrv_replica_flags(s);
192
193         /* update the repsFrom on all partitions */
194         for (p=s->partitions; p; p=p->next) {
195                 struct repsFromToBlob *our_reps;
196                 uint32_t our_count;
197                 WERROR werr;
198                 uint32_t i, j;
199                 bool modified = false;
200
201                 werr = dsdb_loadreps(s->samdb, mem_ctx, p->dn, "repsFrom", &our_reps, &our_count);
202                 if (!W_ERROR_IS_OK(werr)) {
203                         DEBUG(0,(__location__ ": Failed to load repsFrom from %s - %s\n", 
204                                  ldb_dn_get_linearized(p->dn), ldb_errstring(s->samdb)));
205                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
206                 }
207
208                 /* see if the entry already exists */
209                 for (i=0; i<count; i++) {
210                         for (j=0; j<our_count; j++) {
211                                 if (kccsrv_same_source_dsa(&reps[i], &our_reps[j])) {
212                                         /* we already have this one -
213                                            check the replica_flags are right */
214                                         if (replica_flags != our_reps[j].ctr.ctr1.replica_flags) {
215                                                 /* we need to update the old one with
216                                                  * the new flags
217                                                  */
218                                                 our_reps[j].ctr.ctr1.replica_flags = replica_flags;
219                                                 modified = true;
220                                         }
221                                         break;
222                                 }
223                         }
224                         if (j == our_count) {
225                                 /* we don't have the new one - add it
226                                  * if it is a master
227                                  */
228                                 if (!check_MasterNC(p, &reps[i], res)) {
229                                         /* its not a master, we don't
230                                            want to pull from it */
231                                         continue;
232                                 }
233                                 /* we need to add it to our repsFrom */
234                                 our_reps = talloc_realloc(mem_ctx, our_reps, struct repsFromToBlob, our_count+1);
235                                 NT_STATUS_HAVE_NO_MEMORY(our_reps);
236                                 our_reps[our_count] = reps[i];
237                                 our_reps[our_count].ctr.ctr1.replica_flags = replica_flags;
238                                 our_count++;
239                                 modified = true;
240                                 DEBUG(4,(__location__ ": Added repsFrom for %s\n",
241                                          reps[i].ctr.ctr1.other_info->dns_name));
242                         }
243                 }
244
245                 /* remove any stale ones */
246                 for (i=0; i<our_count; i++) {
247                         if (!reps_in_list(&our_reps[i], reps, count) ||
248                             !check_MasterNC(p, &our_reps[i], res)) {
249                                 DEBUG(4,(__location__ ": Removed repsFrom for %s\n",
250                                          our_reps[i].ctr.ctr1.other_info->dns_name));
251                                 memmove(&our_reps[i], &our_reps[i+1], (our_count-(i+1))*sizeof(our_reps[0]));
252                                 our_count--;
253                                 i--;
254                                 modified = true;
255                         }
256                 }
257
258                 if (modified) {
259                         werr = dsdb_savereps(s->samdb, mem_ctx, p->dn, "repsFrom", our_reps, our_count);
260                         if (!W_ERROR_IS_OK(werr)) {
261                                 DEBUG(0,(__location__ ": Failed to save repsFrom to %s - %s\n", 
262                                          ldb_dn_get_linearized(p->dn), ldb_errstring(s->samdb)));
263                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
264                         }
265                         /* dreplsrv should refresh its state */
266                         notify_dreplsrv = true;
267                 }
268
269                 /* remove stale repsTo entries */
270                 modified = false;
271                 werr = dsdb_loadreps(s->samdb, mem_ctx, p->dn, "repsTo", &our_reps, &our_count);
272                 if (!W_ERROR_IS_OK(werr)) {
273                         DEBUG(0,(__location__ ": Failed to load repsTo from %s - %s\n", 
274                                  ldb_dn_get_linearized(p->dn), ldb_errstring(s->samdb)));
275                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
276                 }
277
278                 /* remove any stale ones */
279                 for (i=0; i<our_count; i++) {
280                         if (!reps_in_list(&our_reps[i], reps, count)) {
281                                 DEBUG(4,(__location__ ": Removed repsTo for %s\n",
282                                          our_reps[i].ctr.ctr1.other_info->dns_name));
283                                 memmove(&our_reps[i], &our_reps[i+1], (our_count-(i+1))*sizeof(our_reps[0]));
284                                 our_count--;
285                                 i--;
286                                 modified = true;
287                         }
288                 }
289
290                 if (modified) {
291                         werr = dsdb_savereps(s->samdb, mem_ctx, p->dn, "repsTo", our_reps, our_count);
292                         if (!W_ERROR_IS_OK(werr)) {
293                                 DEBUG(0,(__location__ ": Failed to save repsTo to %s - %s\n", 
294                                          ldb_dn_get_linearized(p->dn), ldb_errstring(s->samdb)));
295                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
296                         }
297                         /* dreplsrv should refresh its state */
298                         notify_dreplsrv = true;
299                 }
300         }
301
302         /* notify dreplsrv toplogy has changed */
303         if (notify_dreplsrv) {
304                 kccsrv_notify_drepl_server(s, mem_ctx);
305         }
306
307         return NT_STATUS_OK;
308
309 }
310
311 /*
312   this is the core of our initial simple KCC
313   We just add a repsFrom entry for all DCs we find that have nTDSDSA
314   objects, except for ourselves
315  */
316 NTSTATUS kccsrv_simple_update(struct kccsrv_service *s, TALLOC_CTX *mem_ctx)
317 {
318         struct ldb_result *res;
319         unsigned int i;
320         int ret;
321         const char *attrs[] = { "objectGUID", "invocationID", "msDS-hasMasterNCs", "hasMasterNCs", NULL };
322         struct repsFromToBlob *reps = NULL;
323         uint32_t count = 0;
324         struct kcc_connection_list *ntds_conn, *dsa_conn;
325
326         ret = ldb_search(s->samdb, mem_ctx, &res, s->config_dn, LDB_SCOPE_SUBTREE, 
327                          attrs, "objectClass=nTDSDSA");
328         if (ret != LDB_SUCCESS) {
329                 DEBUG(0,(__location__ ": Failed nTDSDSA search - %s\n", ldb_errstring(s->samdb)));
330                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
331         }
332
333         /* get the current list of connections */
334         ntds_conn = kccsrv_find_connections(s, mem_ctx);
335
336         dsa_conn = talloc_zero(mem_ctx, struct kcc_connection_list);
337
338         for (i=0; i<res->count; i++) {
339                 struct repsFromTo1 *r1;
340                 struct GUID ntds_guid, invocation_id;
341
342                 ntds_guid = samdb_result_guid(res->msgs[i], "objectGUID");
343                 if (GUID_compare(&ntds_guid, &s->ntds_guid) == 0) {
344                         /* don't replicate with ourselves */
345                         continue;
346                 }
347
348                 invocation_id = samdb_result_guid(res->msgs[i], "invocationID");
349
350                 reps = talloc_realloc(mem_ctx, reps, struct repsFromToBlob, count+1);
351                 NT_STATUS_HAVE_NO_MEMORY(reps);
352
353                 ZERO_STRUCT(reps[count]);
354                 reps[count].version = 1;
355                 r1 = &reps[count].ctr.ctr1;
356
357                 r1->other_info               = talloc_zero(reps, struct repsFromTo1OtherInfo);
358                 r1->other_info->dns_name     = talloc_asprintf(r1->other_info, "%s._msdcs.%s",
359                                                                GUID_string(mem_ctx, &ntds_guid),
360                                                                lpcfg_dnsdomain(s->task->lp_ctx));
361                 r1->source_dsa_obj_guid      = ntds_guid;
362                 r1->source_dsa_invocation_id = invocation_id;
363                 r1->replica_flags = kccsrv_replica_flags(s);
364                 memset(r1->schedule, 0x11, sizeof(r1->schedule));
365
366                 dsa_conn->servers = talloc_realloc(dsa_conn, dsa_conn->servers,
367                                                   struct kcc_connection,
368                                                   dsa_conn->count + 1);
369                 NT_STATUS_HAVE_NO_MEMORY(dsa_conn->servers);
370                 dsa_conn->servers[dsa_conn->count].dsa_guid = r1->source_dsa_obj_guid;
371                 dsa_conn->count++;
372
373                 count++;
374         }
375
376         kccsrv_apply_connections(s, ntds_conn, dsa_conn);
377
378         return kccsrv_add_repsFrom(s, mem_ctx, reps, count, res);
379 }
380
381
382 static void kccsrv_periodic_run(struct kccsrv_service *service);
383
384 static void kccsrv_periodic_handler_te(struct tevent_context *ev, struct tevent_timer *te,
385                                          struct timeval t, void *ptr)
386 {
387         struct kccsrv_service *service = talloc_get_type(ptr, struct kccsrv_service);
388         WERROR status;
389
390         service->periodic.te = NULL;
391
392         kccsrv_periodic_run(service);
393
394         status = kccsrv_periodic_schedule(service, service->periodic.interval);
395         if (!W_ERROR_IS_OK(status)) {
396                 task_server_terminate(service->task, win_errstr(status), true);
397                 return;
398         }
399 }
400
401 WERROR kccsrv_periodic_schedule(struct kccsrv_service *service, uint32_t next_interval)
402 {
403         TALLOC_CTX *tmp_mem;
404         struct tevent_timer *new_te;
405         struct timeval next_time;
406
407         /* prevent looping */
408         if (next_interval == 0) next_interval = 1;
409
410         next_time = timeval_current_ofs(next_interval, 50);
411
412         if (service->periodic.te) {
413                 /*
414                  * if the timestamp of the new event is higher,
415                  * as current next we don't need to reschedule
416                  */
417                 if (timeval_compare(&next_time, &service->periodic.next_event) > 0) {
418                         return WERR_OK;
419                 }
420         }
421
422         /* reset the next scheduled timestamp */
423         service->periodic.next_event = next_time;
424
425         new_te = event_add_timed(service->task->event_ctx, service,
426                                  service->periodic.next_event,
427                                  kccsrv_periodic_handler_te, service);
428         W_ERROR_HAVE_NO_MEMORY(new_te);
429
430         tmp_mem = talloc_new(service);
431         DEBUG(4,("kccsrv_periodic_schedule(%u) %sscheduled for: %s\n",
432                 next_interval,
433                 (service->periodic.te?"re":""),
434                 nt_time_string(tmp_mem, timeval_to_nttime(&next_time))));
435         talloc_free(tmp_mem);
436
437         talloc_free(service->periodic.te);
438         service->periodic.te = new_te;
439
440         return WERR_OK;
441 }
442
443 static void kccsrv_periodic_run(struct kccsrv_service *service)
444 {
445         TALLOC_CTX *mem_ctx;
446         NTSTATUS status;
447
448         DEBUG(4,("kccsrv_periodic_run(): simple update\n"));
449
450         mem_ctx = talloc_new(service);
451         status = kccsrv_simple_update(service, mem_ctx);
452         if (!NT_STATUS_IS_OK(status)) {
453                 DEBUG(0,("kccsrv_simple_update failed - %s\n", nt_errstr(status)));
454         }
455
456         status = kccsrv_check_deleted(service, mem_ctx);
457         if (!NT_STATUS_IS_OK(status)) {
458                 DEBUG(0,("kccsrv_check_deleted failed - %s\n", nt_errstr(status)));
459         }
460         talloc_free(mem_ctx);
461 }