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