ldb: use #include <ldb.h> for ldb
[kai/samba.git] / source4 / nbt_server / wins / winsdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    WINS database routines
5
6    Copyright (C) Andrew Tridgell        2005
7    Copyright (C) Stefan Metzmacher      2005
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 "nbt_server/nbt_server.h"
25 #include "nbt_server/wins/winsdb.h"
26 #include <ldb.h>
27 #include <ldb_errors.h>
28 #include "librpc/gen_ndr/ndr_nbt.h"
29 #include "system/time.h"
30 #include "ldb_wrap.h"
31 #include "system/network.h"
32 #include "lib/socket/netif.h"
33 #include "param/param.h"
34
35 uint64_t winsdb_get_maxVersion(struct winsdb_handle *h)
36 {
37         int ret;
38         struct ldb_context *ldb = h->ldb;
39         struct ldb_dn *dn;
40         struct ldb_result *res = NULL;
41         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
42         uint64_t maxVersion = 0;
43
44         dn = ldb_dn_new(tmp_ctx, ldb, "CN=VERSION");
45         if (!dn) goto failed;
46
47         /* find the record in the WINS database */
48         ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL);
49         if (ret != LDB_SUCCESS) goto failed;
50         if (res->count > 1) goto failed;
51
52         if (res->count == 1) {
53                 maxVersion = ldb_msg_find_attr_as_uint64(res->msgs[0], "maxVersion", 0);
54         }
55
56 failed:
57         talloc_free(tmp_ctx);
58         return maxVersion;
59 }
60
61 /*
62  if newVersion == 0 return the old maxVersion + 1 and save it
63  if newVersion > 0 return MAX(oldMaxVersion, newMaxVersion) and save it
64 */
65 uint64_t winsdb_set_maxVersion(struct winsdb_handle *h, uint64_t newMaxVersion)
66 {
67         int trans;
68         int ret;
69         struct ldb_dn *dn;
70         struct ldb_result *res = NULL;
71         struct ldb_message *msg = NULL;
72         struct ldb_context *wins_db = h->ldb;
73         TALLOC_CTX *tmp_ctx = talloc_new(wins_db);
74         uint64_t oldMaxVersion = 0;
75
76         trans = ldb_transaction_start(wins_db);
77         if (trans != LDB_SUCCESS) goto failed;
78
79         dn = ldb_dn_new(tmp_ctx, wins_db, "CN=VERSION");
80         if (!dn) goto failed;
81
82         /* find the record in the WINS database */
83         ret = ldb_search(wins_db, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL);
84         if (ret != LDB_SUCCESS) goto failed;
85         if (res->count > 1) goto failed;
86
87         if (res->count == 1) {
88                 oldMaxVersion = ldb_msg_find_attr_as_uint64(res->msgs[0], "maxVersion", 0);
89         }
90
91         if (newMaxVersion == 0) {
92                 newMaxVersion = oldMaxVersion + 1;
93         } else {
94                 newMaxVersion = MAX(oldMaxVersion, newMaxVersion);
95         }
96
97         msg = ldb_msg_new(tmp_ctx);
98         if (!msg) goto failed;
99         msg->dn = dn;
100
101
102         ret = ldb_msg_add_empty(msg, "objectClass", LDB_FLAG_MOD_REPLACE, NULL);
103         if (ret != LDB_SUCCESS) goto failed;
104         ret = ldb_msg_add_string(msg, "objectClass", "winsMaxVersion");
105         if (ret != LDB_SUCCESS) goto failed;
106         ret = ldb_msg_add_empty(msg, "maxVersion", LDB_FLAG_MOD_REPLACE, NULL);
107         if (ret != LDB_SUCCESS) goto failed;
108         ret = ldb_msg_add_fmt(msg, "maxVersion", "%llu", (long long)newMaxVersion);
109         if (ret != LDB_SUCCESS) goto failed;
110
111         ret = ldb_modify(wins_db, msg);
112         if (ret != LDB_SUCCESS) ret = ldb_add(wins_db, msg);
113         if (ret != LDB_SUCCESS) goto failed;
114
115         trans = ldb_transaction_commit(wins_db);
116         if (trans != LDB_SUCCESS) goto failed;
117
118         talloc_free(tmp_ctx);
119         return newMaxVersion;
120
121 failed:
122         if (trans == LDB_SUCCESS) ldb_transaction_cancel(wins_db);
123         talloc_free(tmp_ctx);
124         return 0;
125 }
126
127 uint64_t winsdb_get_seqnumber(struct winsdb_handle *h)
128 {
129         int ret;
130         struct ldb_context *ldb = h->ldb;
131         struct ldb_dn *dn;
132         struct ldb_result *res = NULL;
133         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
134         uint64_t seqnumber = 0;
135
136         dn = ldb_dn_new(tmp_ctx, ldb, "@BASEINFO");
137         if (!dn) goto failed;
138
139         /* find the record in the WINS database */
140         ret = ldb_search(ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL);
141         if (ret != LDB_SUCCESS) goto failed;
142         if (res->count > 1) goto failed;
143
144         if (res->count == 1) {
145                 seqnumber = ldb_msg_find_attr_as_uint64(res->msgs[0], "sequenceNumber", 0);
146         }
147
148 failed:
149         talloc_free(tmp_ctx);
150         return seqnumber;
151 }
152
153 /*
154   return a DN for a nbt_name
155 */
156 static struct ldb_dn *winsdb_dn(TALLOC_CTX *mem_ctx, struct ldb_context *ldb,
157                                 const struct nbt_name *name)
158 {
159         struct ldb_dn *dn;
160
161         dn = ldb_dn_new_fmt(mem_ctx, ldb, "type=0x%02X", name->type);
162         if (ldb_dn_is_valid(dn) && name->name && *name->name) {
163                 ldb_dn_add_child_fmt(dn, "name=%s", name->name);
164         }
165         if (ldb_dn_is_valid(dn) && name->scope && *name->scope) {
166                 ldb_dn_add_child_fmt(dn, "scope=%s", name->scope);
167         }
168         return dn;
169 }
170
171 static NTSTATUS winsdb_nbt_name(TALLOC_CTX *mem_ctx, struct ldb_dn *dn, struct nbt_name **_name)
172 {
173         NTSTATUS status;
174         struct nbt_name *name;
175         unsigned int comp_num;
176         uint32_t cur = 0;
177
178         name = talloc(mem_ctx, struct nbt_name);
179         if (!name) {
180                 status = NT_STATUS_NO_MEMORY;
181                 goto failed;
182         }
183
184         comp_num = ldb_dn_get_comp_num(dn);
185
186         if (comp_num > 3) {
187                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
188                 goto failed;
189         }
190
191         if (comp_num > cur && strcasecmp("scope", ldb_dn_get_component_name(dn, cur)) == 0) {
192                 name->scope     = (const char *)talloc_strdup(name, (char *)ldb_dn_get_component_val(dn, cur)->data);
193                 cur++;
194         } else {
195                 name->scope     = NULL;
196         }
197
198         if (comp_num > cur && strcasecmp("name", ldb_dn_get_component_name(dn, cur)) == 0) {
199                 name->name      = (const char *)talloc_strdup(name, (char *)ldb_dn_get_component_val(dn, cur)->data);
200                 cur++;
201         } else {
202                 name->name      = talloc_strdup(name, "");
203                 if (!name->name) {
204                         status = NT_STATUS_NO_MEMORY;
205                         goto failed;
206                 }
207         }
208
209         if (comp_num > cur && strcasecmp("type", ldb_dn_get_component_name(dn, cur)) == 0) {
210                 name->type      = strtoul((char *)ldb_dn_get_component_val(dn, cur)->data, NULL, 0);
211                 cur++;
212         } else {
213                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
214                 goto failed;
215         }
216
217         *_name = name;
218         return NT_STATUS_OK;
219 failed:
220         talloc_free(name);
221         return status;
222 }
223
224 /*
225  decode the winsdb_addr("address") attribute:
226  "172.31.1.1" or 
227  "172.31.1.1;winsOwner:172.31.9.202;expireTime:20050923032330.0Z;"
228  are valid records
229 */
230 static NTSTATUS winsdb_addr_decode(struct winsdb_handle *h, struct winsdb_record *rec, struct ldb_val *val,
231                                    TALLOC_CTX *mem_ctx, struct winsdb_addr **_addr)
232 {
233         NTSTATUS status;
234         struct winsdb_addr *addr;
235         const char *address;
236         const char *wins_owner;
237         const char *expire_time;
238         char *p;
239
240         addr = talloc(mem_ctx, struct winsdb_addr);
241         if (!addr) {
242                 status = NT_STATUS_NO_MEMORY;
243                 goto failed;
244         }
245
246         address = (char *)val->data;
247
248         p = strchr(address, ';');
249         if (!p) {
250                 /* support old entries, with only the address */
251                 addr->address           = (const char *)talloc_steal(addr, val->data);
252                 addr->wins_owner        = talloc_reference(addr, rec->wins_owner);
253                 if (!addr->wins_owner) {
254                         status = NT_STATUS_NO_MEMORY;
255                         goto failed;
256                 }
257                 addr->expire_time       = rec->expire_time;
258                 *_addr = addr;
259                 return NT_STATUS_OK;
260         }
261
262         *p = '\0'; p++;
263         addr->address = talloc_strdup(addr, address);
264         if (!addr->address) {
265                 status = NT_STATUS_NO_MEMORY;
266                 goto failed;
267         }
268
269         if (strncmp("winsOwner:", p, 10) != 0) {
270                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
271                 goto failed;
272         }
273         wins_owner = p + 10;
274         p = strchr(wins_owner, ';');
275         if (!p) {
276                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
277                 goto failed;
278         }
279
280         *p = '\0';p++;
281         if (strcmp(wins_owner, "0.0.0.0") == 0) {
282                 wins_owner = h->local_owner;
283         }
284         addr->wins_owner = talloc_strdup(addr, wins_owner);
285         if (!addr->wins_owner) {
286                 status = NT_STATUS_NO_MEMORY;
287                 goto failed;
288         }
289
290         if (strncmp("expireTime:", p, 11) != 0) {
291                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
292                 goto failed;
293         }
294
295         expire_time = p + 11;
296         p = strchr(expire_time, ';');
297         if (!p) {
298                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
299                 goto failed;
300         }
301
302         *p = '\0';p++;
303         addr->expire_time = ldb_string_to_time(expire_time);
304
305         *_addr = addr;
306         return NT_STATUS_OK;
307 failed:
308         talloc_free(addr);
309         return status;
310 }
311
312 /*
313  encode the winsdb_addr("address") attribute like this:
314  non-static record:
315  "172.31.1.1;winsOwner:172.31.9.202;expireTime:20050923032330.0Z;"
316  static record:
317  "172.31.1.1"
318 */
319 static int ldb_msg_add_winsdb_addr(struct ldb_message *msg, struct winsdb_record *rec,
320                                    const char *attr_name, struct winsdb_addr *addr)
321 {
322         const char *str;
323
324         if (rec->is_static) {
325                 str = talloc_strdup(msg, addr->address);
326                 if (!str) return LDB_ERR_OPERATIONS_ERROR;
327         } else {
328                 char *expire_time;
329                 expire_time = ldb_timestring(msg, addr->expire_time);
330                 if (!expire_time) return LDB_ERR_OPERATIONS_ERROR;
331                 str = talloc_asprintf(msg, "%s;winsOwner:%s;expireTime:%s;",
332                                       addr->address, addr->wins_owner,
333                                       expire_time);
334                 talloc_free(expire_time);
335                 if (!str) return LDB_ERR_OPERATIONS_ERROR;
336         }
337
338         return ldb_msg_add_string(msg, attr_name, str);
339 }
340
341 struct winsdb_addr **winsdb_addr_list_make(TALLOC_CTX *mem_ctx)
342 {
343         struct winsdb_addr **addresses;
344
345         addresses = talloc_array(mem_ctx, struct winsdb_addr *, 1);
346         if (!addresses) return NULL;
347
348         addresses[0] = NULL;
349
350         return addresses;
351 }
352
353 static int winsdb_addr_sort_list (struct winsdb_addr **p1, struct winsdb_addr **p2, void *opaque)
354 {
355         struct winsdb_addr *a1 = talloc_get_type(*p1, struct winsdb_addr);
356         struct winsdb_addr *a2 = talloc_get_type(*p2, struct winsdb_addr);
357         struct winsdb_handle *h= talloc_get_type(opaque, struct winsdb_handle);
358         bool a1_owned = false;
359         bool a2_owned = false;
360
361         /*
362          * first the owned addresses with the newest to the oldest address
363          * then the replica addresses with the newest to the oldest address
364          */
365         if (a2->expire_time != a1->expire_time) {
366                 return a2->expire_time - a1->expire_time;
367         }
368
369         if (strcmp(a2->wins_owner, h->local_owner) == 0) {
370                 a2_owned = true;
371         }
372
373         if (strcmp(a1->wins_owner, h->local_owner) == 0) {
374                 a1_owned = true;
375         }
376
377         return a2_owned - a1_owned;
378 }
379
380 struct winsdb_addr **winsdb_addr_list_add(struct winsdb_handle *h, const struct winsdb_record *rec,
381                                           struct winsdb_addr **addresses, const char *address,
382                                           const char *wins_owner, time_t expire_time,
383                                           bool is_name_registration)
384 {
385         struct winsdb_addr *old_addr = NULL;
386         size_t len = 0;
387         size_t i;
388         bool found_old_replica = false;
389
390         /*
391          * count the addresses and maybe
392          * find an old entry for the new address
393          */
394         for (i=0; addresses[i]; i++) {
395                 if (old_addr) continue;
396                 if (strcmp(addresses[i]->address, address) == 0) {
397                         old_addr = addresses[i];
398                 }
399         }
400         len = i;
401
402         /*
403          * the address is already there
404          * and we can replace it
405          */
406         if (old_addr) {
407                 goto remove_old_addr;
408         }
409
410         /*
411          * if we don't have 25 addresses already,
412          * we can just add the new address
413          */
414         if (len < 25) {
415                 goto add_new_addr;
416         }
417
418         /*
419          * if we haven't found the address,
420          * and we have already have 25 addresses
421          * if so then we need to do the following:
422          * - if it isn't a name registration, then just ignore the new address
423          * - if it is a name registration, then first search for 
424          *   the oldest replica and if there's no replica address
425          *   search the oldest owned address
426          */
427         if (!is_name_registration) {
428                 return addresses;
429         }
430
431         /*
432          * find the oldest replica address, if there's no replica
433          * record at all, find the oldest owned address
434          */
435         for (i=0; addresses[i]; i++) {
436                 bool cur_is_replica = false;
437                 /* find out if the current address is a replica */
438                 if (strcmp(addresses[i]->wins_owner, h->local_owner) != 0) {
439                         cur_is_replica = true;
440                 }
441
442                 /*
443                  * if we already found a replica address and the current address
444                  * is not a replica, then skip it
445                  */
446                 if (found_old_replica && !cur_is_replica) continue;
447
448                 /*
449                  * if we found the first replica address, reset the address
450                  * that would be replaced
451                  */
452                 if (!found_old_replica && cur_is_replica) {
453                         found_old_replica = true;
454                         old_addr = addresses[i];
455                         continue;
456                 }
457
458                 /*
459                  * if the first address isn't a replica, just start with 
460                  * the first one
461                  */
462                 if (!old_addr) {
463                         old_addr = addresses[i];
464                         continue;
465                 }
466
467                 /*
468                  * see if we find an older address
469                  */
470                 if (addresses[i]->expire_time < old_addr->expire_time) {
471                         old_addr = addresses[i];
472                         continue;
473                 }
474         }
475
476 remove_old_addr:
477         winsdb_addr_list_remove(addresses, old_addr->address);
478         len --;
479
480 add_new_addr:
481         addresses = talloc_realloc(addresses, addresses, struct winsdb_addr *, len + 2);
482         if (!addresses) return NULL;
483
484         addresses[len] = talloc(addresses, struct winsdb_addr);
485         if (!addresses[len]) {
486                 talloc_free(addresses);
487                 return NULL;
488         }
489
490         addresses[len]->address = talloc_strdup(addresses[len], address);
491         if (!addresses[len]->address) {
492                 talloc_free(addresses);
493                 return NULL;
494         }
495
496         addresses[len]->wins_owner = talloc_strdup(addresses[len], wins_owner);
497         if (!addresses[len]->wins_owner) {
498                 talloc_free(addresses);
499                 return NULL;
500         }
501
502         addresses[len]->expire_time = expire_time;
503
504         addresses[len+1] = NULL;
505
506         LDB_TYPESAFE_QSORT(addresses, len+1, h, winsdb_addr_sort_list);
507
508         return addresses;
509 }
510
511 void winsdb_addr_list_remove(struct winsdb_addr **addresses, const char *address)
512 {
513         size_t i;
514
515         for (i=0; addresses[i]; i++) {
516                 if (strcmp(addresses[i]->address, address) == 0) {
517                         break;
518                 }
519         }
520
521         for (; addresses[i]; i++) {
522                 addresses[i] = addresses[i+1];
523         }
524
525         return;
526 }
527
528 struct winsdb_addr *winsdb_addr_list_check(struct winsdb_addr **addresses, const char *address)
529 {
530         size_t i;
531
532         for (i=0; addresses[i]; i++) {
533                 if (strcmp(addresses[i]->address, address) == 0) {
534                         return addresses[i];
535                 }
536         }
537
538         return NULL;
539 }
540
541 size_t winsdb_addr_list_length(struct winsdb_addr **addresses)
542 {
543         size_t i;
544         for (i=0; addresses[i]; i++);
545         return i;
546 }
547
548 const char **winsdb_addr_string_list(TALLOC_CTX *mem_ctx, struct winsdb_addr **addresses)
549 {
550         size_t len = winsdb_addr_list_length(addresses);
551         const char **str_list=NULL;
552         size_t i;
553
554         for (i=0; i < len; i++) {
555                 str_list = str_list_add(str_list, addresses[i]->address);
556                 if (!str_list[i]) {
557                         return NULL;
558                 }
559         }
560         talloc_steal(mem_ctx, str_list);
561         return str_list;
562 }
563
564 /*
565   load a WINS entry from the database
566 */
567 NTSTATUS winsdb_lookup(struct winsdb_handle *h, 
568                        const struct nbt_name *name,
569                        TALLOC_CTX *mem_ctx,
570                        struct winsdb_record **_rec)
571 {
572         NTSTATUS status;
573         struct ldb_result *res = NULL;
574         int ret;
575         struct winsdb_record *rec;
576         struct ldb_context *wins_db = h->ldb;
577         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
578         time_t now = time(NULL);
579
580         /* find the record in the WINS database */
581         ret = ldb_search(wins_db, tmp_ctx, &res,
582                          winsdb_dn(tmp_ctx, wins_db, name),
583                          LDB_SCOPE_BASE, NULL, NULL);
584
585         if (ret != LDB_SUCCESS || res->count > 1) {
586                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
587                 goto failed;
588         } else if (res->count== 0) {
589                 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
590                 goto failed;
591         }
592
593         status = winsdb_record(h, res->msgs[0], tmp_ctx, now, &rec);
594         if (!NT_STATUS_IS_OK(status)) goto failed;
595
596         talloc_steal(mem_ctx, rec);
597         talloc_free(tmp_ctx);
598         *_rec = rec;
599         return NT_STATUS_OK;
600
601 failed:
602         talloc_free(tmp_ctx);
603         return status;
604 }
605
606 NTSTATUS winsdb_record(struct winsdb_handle *h, struct ldb_message *msg, TALLOC_CTX *mem_ctx, time_t now, struct winsdb_record **_rec)
607 {
608         NTSTATUS status;
609         struct winsdb_record *rec;
610         struct ldb_message_element *el;
611         struct nbt_name *name;
612         uint32_t i, j, num_values;
613
614         rec = talloc(mem_ctx, struct winsdb_record);
615         if (rec == NULL) {
616                 status = NT_STATUS_NO_MEMORY;
617                 goto failed;
618         }
619
620         status = winsdb_nbt_name(rec, msg->dn, &name);
621         if (!NT_STATUS_IS_OK(status)) goto failed;
622
623         if (strlen(name->name) > 15) {
624                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
625                 goto failed;
626         }
627         if (name->scope && strlen(name->scope) > 238) {
628                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
629                 goto failed;
630         }
631
632         /* parse it into a more convenient winsdb_record structure */
633         rec->name               = name;
634         rec->type               = ldb_msg_find_attr_as_int(msg, "recordType", WREPL_TYPE_UNIQUE);
635         rec->state              = ldb_msg_find_attr_as_int(msg, "recordState", WREPL_STATE_RELEASED);
636         rec->node               = ldb_msg_find_attr_as_int(msg, "nodeType", WREPL_NODE_B);
637         rec->is_static          = ldb_msg_find_attr_as_int(msg, "isStatic", 0);
638         rec->expire_time        = ldb_string_to_time(ldb_msg_find_attr_as_string(msg, "expireTime", NULL));
639         rec->version            = ldb_msg_find_attr_as_uint64(msg, "versionID", 0);
640         rec->wins_owner         = ldb_msg_find_attr_as_string(msg, "winsOwner", NULL);
641         rec->registered_by      = ldb_msg_find_attr_as_string(msg, "registeredBy", NULL);
642         talloc_steal(rec, rec->wins_owner);
643         talloc_steal(rec, rec->registered_by);
644
645         if (!rec->wins_owner || strcmp(rec->wins_owner, "0.0.0.0") == 0) {
646                 rec->wins_owner = h->local_owner;
647         }
648
649         el = ldb_msg_find_element(msg, "address");
650         if (el) {
651                 num_values = el->num_values;
652         } else {
653                 num_values = 0;
654         }
655
656         if (rec->type == WREPL_TYPE_UNIQUE || rec->type == WREPL_TYPE_GROUP) {
657                 if (num_values != 1) {
658                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
659                         goto failed;
660                 }
661         }
662         if (rec->state == WREPL_STATE_ACTIVE) {
663                 if (num_values < 1) {
664                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
665                         goto failed;
666                 }
667         }
668         if (num_values > 25) {
669                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
670                 goto failed;
671         }
672
673         rec->addresses     = talloc_array(rec, struct winsdb_addr *, num_values+1);
674         if (rec->addresses == NULL) {
675                 status = NT_STATUS_NO_MEMORY;
676                 goto failed;
677         }
678
679         for (i=0,j=0;i<num_values;i++) {
680                 bool we_are_owner = false;
681
682                 status = winsdb_addr_decode(h, rec, &el->values[i], rec->addresses, &rec->addresses[j]);
683                 if (!NT_STATUS_IS_OK(status)) goto failed;
684
685                 if (strcmp(rec->addresses[j]->wins_owner, h->local_owner) == 0) {
686                         we_are_owner = true;
687                 }
688
689                 /*
690                  * the record isn't static and is active
691                  * then don't add the address if it's expired,
692                  * but only if we're the owner of the address
693                  *
694                  * This is important for SGROUP records,
695                  * because each server thinks he's the owner of the
696                  * record and the record isn't replicated on a
697                  * name_refresh. So addresses owned by another owner
698                  * could expire, but we still need to return them
699                  * (as windows does).
700                  */
701                 if (!rec->is_static &&
702                     rec->addresses[j]->expire_time <= now &&
703                     rec->state == WREPL_STATE_ACTIVE &&
704                     we_are_owner) {
705                         DEBUG(5,("WINS: expiring name addr %s of %s (expired at %s)\n", 
706                                  rec->addresses[j]->address, nbt_name_string(rec->addresses[j], rec->name),
707                                  timestring(rec->addresses[j], rec->addresses[j]->expire_time)));
708                         talloc_free(rec->addresses[j]);
709                         rec->addresses[j] = NULL;
710                         continue;
711                 }
712                 j++;
713         }
714         rec->addresses[j] = NULL;
715         num_values = j;
716
717         if (rec->is_static && rec->state == WREPL_STATE_ACTIVE) {
718                 rec->expire_time = get_time_t_max();
719                 for (i=0;rec->addresses[i];i++) {
720                         rec->addresses[i]->expire_time = rec->expire_time;
721                 }
722         }
723
724         if (rec->state == WREPL_STATE_ACTIVE) {
725                 if (num_values < 1) {
726                         DEBUG(5,("WINS: expiring name %s (because it has no active addresses)\n", 
727                                  nbt_name_string(mem_ctx, rec->name)));
728                         rec->state = WREPL_STATE_RELEASED;
729                 }
730         }
731
732         *_rec = rec;
733         return NT_STATUS_OK;
734 failed:
735         if (NT_STATUS_EQUAL(NT_STATUS_INTERNAL_DB_CORRUPTION, status)) {
736                 DEBUG(1,("winsdb_record: corrupted record: %s\n", ldb_dn_get_linearized(msg->dn)));
737         }
738         talloc_free(rec);
739         return status;
740 }
741
742 /*
743   form a ldb_message from a winsdb_record
744 */
745 static struct ldb_message *winsdb_message(struct ldb_context *ldb,
746                                           struct winsdb_record *rec,
747                                           TALLOC_CTX *mem_ctx)
748 {
749         int i, ret;
750         size_t addr_count;
751         const char *expire_time;
752         struct ldb_message *msg = ldb_msg_new(mem_ctx);
753         if (msg == NULL) goto failed;
754
755         /* make sure we don't put in corrupted records */
756         addr_count = winsdb_addr_list_length(rec->addresses);
757         if (rec->state == WREPL_STATE_ACTIVE && addr_count == 0) {
758                 rec->state = WREPL_STATE_RELEASED;
759         }
760         if (rec->type == WREPL_TYPE_UNIQUE && addr_count > 1) {
761                 rec->type = WREPL_TYPE_MHOMED;
762         }
763
764         expire_time = ldb_timestring(msg, rec->expire_time);
765         if (!expire_time) {
766                 goto failed;
767         }
768
769         msg->dn = winsdb_dn(msg, ldb, rec->name);
770         if (msg->dn == NULL) goto failed;
771         ret = ldb_msg_add_fmt(msg, "type", "0x%02X", rec->name->type);
772         if (rec->name->name && *rec->name->name) {
773                 ret |= ldb_msg_add_string(msg, "name", rec->name->name);
774         }
775         if (rec->name->scope && *rec->name->scope) {
776                 ret |= ldb_msg_add_string(msg, "scope", rec->name->scope);
777         }
778         ret |= ldb_msg_add_fmt(msg, "objectClass", "winsRecord");
779         ret |= ldb_msg_add_fmt(msg, "recordType", "%u", rec->type);
780         ret |= ldb_msg_add_fmt(msg, "recordState", "%u", rec->state);
781         ret |= ldb_msg_add_fmt(msg, "nodeType", "%u", rec->node);
782         ret |= ldb_msg_add_fmt(msg, "isStatic", "%u", rec->is_static);
783         ret |= ldb_msg_add_empty(msg, "expireTime", 0, NULL);
784         if (!(rec->is_static && rec->state == WREPL_STATE_ACTIVE)) {
785                 ret |= ldb_msg_add_string(msg, "expireTime", expire_time);
786         }
787         ret |= ldb_msg_add_fmt(msg, "versionID", "%llu", (long long)rec->version);
788         ret |= ldb_msg_add_string(msg, "winsOwner", rec->wins_owner);
789         ret |= ldb_msg_add_empty(msg, "address", 0, NULL);
790         for (i=0;rec->addresses[i];i++) {
791                 ret |= ldb_msg_add_winsdb_addr(msg, rec, "address", rec->addresses[i]);
792         }
793         if (rec->registered_by) {
794                 ret |= ldb_msg_add_empty(msg, "registeredBy", 0, NULL);
795                 ret |= ldb_msg_add_string(msg, "registeredBy", rec->registered_by);
796         }
797         if (ret != LDB_SUCCESS) goto failed;
798         return msg;
799
800 failed:
801         talloc_free(msg);
802         return NULL;
803 }
804
805 /*
806   save a WINS record into the database
807 */
808 uint8_t winsdb_add(struct winsdb_handle *h, struct winsdb_record *rec, uint32_t flags)
809 {
810         struct ldb_message *msg;
811         struct ldb_context *wins_db = h->ldb;
812         TALLOC_CTX *tmp_ctx = talloc_new(wins_db);
813         int trans = -1;
814         int ret;
815
816         trans = ldb_transaction_start(wins_db);
817         if (trans != LDB_SUCCESS) goto failed;
818
819         if (flags & WINSDB_FLAG_ALLOC_VERSION) {
820                 /* passing '0' means auto-allocate a new one */
821                 rec->version = winsdb_set_maxVersion(h, 0);
822                 if (rec->version == 0) goto failed;
823         }
824         if (flags & WINSDB_FLAG_TAKE_OWNERSHIP) {
825                 rec->wins_owner = h->local_owner;
826         }
827
828         msg = winsdb_message(wins_db, rec, tmp_ctx);
829         if (msg == NULL) goto failed;
830         ret = ldb_add(wins_db, msg);
831         if (ret != LDB_SUCCESS) goto failed;
832
833         trans = ldb_transaction_commit(wins_db);
834         if (trans != LDB_SUCCESS) goto failed;
835
836         wins_hook(h, rec, WINS_HOOK_ADD, h->hook_script);
837
838         talloc_free(tmp_ctx);
839         return NBT_RCODE_OK;
840
841 failed:
842         if (trans == LDB_SUCCESS) ldb_transaction_cancel(wins_db);
843         talloc_free(tmp_ctx);
844         return NBT_RCODE_SVR;
845 }
846
847
848 /*
849   modify a WINS record in the database
850 */
851 uint8_t winsdb_modify(struct winsdb_handle *h, struct winsdb_record *rec, uint32_t flags)
852 {
853         struct ldb_message *msg;
854         struct ldb_context *wins_db = h->ldb;
855         TALLOC_CTX *tmp_ctx = talloc_new(wins_db);
856         int trans;
857         int ret;
858         unsigned int i;
859
860         trans = ldb_transaction_start(wins_db);
861         if (trans != LDB_SUCCESS) goto failed;
862
863         if (flags & WINSDB_FLAG_ALLOC_VERSION) {
864                 /* passing '0' means auto-allocate a new one */
865                 rec->version = winsdb_set_maxVersion(h, 0);
866                 if (rec->version == 0) goto failed;
867         }
868         if (flags & WINSDB_FLAG_TAKE_OWNERSHIP) {
869                 rec->wins_owner = h->local_owner;
870         }
871
872         msg = winsdb_message(wins_db, rec, tmp_ctx);
873         if (msg == NULL) goto failed;
874
875         for (i=0;i<msg->num_elements;i++) {
876                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
877         }
878
879         ret = ldb_modify(wins_db, msg);
880         if (ret != LDB_SUCCESS) goto failed;
881
882         trans = ldb_transaction_commit(wins_db);
883         if (trans != LDB_SUCCESS) goto failed;
884
885         wins_hook(h, rec, WINS_HOOK_MODIFY, h->hook_script);
886
887         talloc_free(tmp_ctx);
888         return NBT_RCODE_OK;
889
890 failed:
891         if (trans == LDB_SUCCESS) ldb_transaction_cancel(wins_db);
892         talloc_free(tmp_ctx);
893         return NBT_RCODE_SVR;
894 }
895
896
897 /*
898   delete a WINS record from the database
899 */
900 uint8_t winsdb_delete(struct winsdb_handle *h, struct winsdb_record *rec)
901 {
902         struct ldb_context *wins_db = h->ldb;
903         TALLOC_CTX *tmp_ctx = talloc_new(wins_db);
904         struct ldb_dn *dn;
905         int trans;
906         int ret;
907
908         trans = ldb_transaction_start(wins_db);
909         if (trans != LDB_SUCCESS) goto failed;
910
911         dn = winsdb_dn(tmp_ctx, wins_db, rec->name);
912         if (dn == NULL) goto failed;
913
914         ret = ldb_delete(wins_db, dn);
915         if (ret != LDB_SUCCESS) goto failed;
916
917         trans = ldb_transaction_commit(wins_db);
918         if (trans != LDB_SUCCESS) goto failed;
919
920         wins_hook(h, rec, WINS_HOOK_DELETE, h->hook_script);
921
922         talloc_free(tmp_ctx);
923         return NBT_RCODE_OK;
924
925 failed:
926         if (trans == LDB_SUCCESS) ldb_transaction_cancel(wins_db);
927         talloc_free(tmp_ctx);
928         return NBT_RCODE_SVR;
929 }
930
931 static bool winsdb_check_or_add_module_list(struct tevent_context *ev_ctx, 
932                                             struct loadparm_context *lp_ctx, struct winsdb_handle *h)
933 {
934         int trans;
935         int ret;
936         struct ldb_dn *dn;
937         struct ldb_result *res = NULL;
938         struct ldb_message *msg = NULL;
939         TALLOC_CTX *tmp_ctx = talloc_new(h);
940         unsigned int flags = 0;
941
942         trans = ldb_transaction_start(h->ldb);
943         if (trans != LDB_SUCCESS) goto failed;
944
945         /* check if we have a special @MODULES record already */
946         dn = ldb_dn_new(tmp_ctx, h->ldb, "@MODULES");
947         if (!dn) goto failed;
948
949         /* find the record in the WINS database */
950         ret = ldb_search(h->ldb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, NULL, NULL);
951         if (ret != LDB_SUCCESS) goto failed;
952
953         if (res->count > 0) goto skip;
954
955         /* if there's no record, add one */
956         msg = ldb_msg_new(tmp_ctx);
957         if (!msg) goto failed;
958         msg->dn = dn;
959
960         ret = ldb_msg_add_string(msg, "@LIST", "wins_ldb");
961         if (ret != LDB_SUCCESS) goto failed;
962
963         ret = ldb_add(h->ldb, msg);
964         if (ret != LDB_SUCCESS) goto failed;
965
966         trans = ldb_transaction_commit(h->ldb);
967         if (trans != LDB_SUCCESS) goto failed;
968
969         /* close and reopen the database, with the modules */
970         trans = LDB_ERR_OTHER;
971         talloc_free(h->ldb);
972         h->ldb = NULL;
973
974         if (lpcfg_parm_bool(lp_ctx, NULL,"winsdb", "nosync", false)) {
975                 flags |= LDB_FLG_NOSYNC;
976         }
977
978         h->ldb = ldb_wrap_connect(h, ev_ctx, lp_ctx, lock_path(h, lp_ctx, lpcfg_wins_url(lp_ctx)),
979                                   NULL, NULL, flags);
980         if (!h->ldb) goto failed;
981
982         talloc_free(tmp_ctx);
983         return true;
984
985 skip:
986         if (trans == LDB_SUCCESS) ldb_transaction_cancel(h->ldb);
987         talloc_free(tmp_ctx);
988         return true;
989
990 failed:
991         if (trans == LDB_SUCCESS) ldb_transaction_cancel(h->ldb);
992         talloc_free(tmp_ctx);
993         return false;
994 }
995
996 struct winsdb_handle *winsdb_connect(TALLOC_CTX *mem_ctx, 
997                                      struct tevent_context *ev_ctx,
998                                      struct loadparm_context *lp_ctx,
999                                      const char *owner,
1000                                      enum winsdb_handle_caller caller)
1001 {
1002         struct winsdb_handle *h = NULL;
1003         unsigned int flags = 0;
1004         bool ret;
1005         int ldb_err;
1006
1007         h = talloc_zero(mem_ctx, struct winsdb_handle);
1008         if (!h) return NULL;
1009
1010         if (lpcfg_parm_bool(lp_ctx, NULL,"winsdb", "nosync", false)) {
1011                 flags |= LDB_FLG_NOSYNC;
1012         }
1013
1014         h->ldb = ldb_wrap_connect(h, ev_ctx, lp_ctx, lock_path(h, lp_ctx, lpcfg_wins_url(lp_ctx)),
1015                                   NULL, NULL, flags);
1016         if (!h->ldb) goto failed;
1017
1018         h->caller = caller;
1019         h->hook_script = lpcfg_wins_hook(lp_ctx);
1020
1021         h->local_owner = talloc_strdup(h, owner);
1022         if (!h->local_owner) goto failed;
1023
1024         /* make sure the module list is available and used */
1025         ret = winsdb_check_or_add_module_list(ev_ctx, lp_ctx, h);
1026         if (!ret) goto failed;
1027
1028         ldb_err = ldb_set_opaque(h->ldb, "winsdb_handle", h);
1029         if (ldb_err != LDB_SUCCESS) goto failed;
1030
1031         return h;
1032 failed:
1033         talloc_free(h);
1034         return NULL;
1035 }
1036