r13924: Split more prototypes out of include/proto.h + initial work on header
[bbaumbach/samba-autobuild/.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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "nbt_server/nbt_server.h"
26 #include "nbt_server/wins/winsdb.h"
27 #include "lib/ldb/include/ldb.h"
28 #include "lib/ldb/include/ldb_errors.h"
29 #include "system/time.h"
30 #include "db_wrap.h"
31 #include "system/network.h"
32 #include "netif/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_explode(tmp_ctx, "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_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_explode(tmp_ctx, "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         if (res->count > 1) goto failed;
88
89         talloc_steal(tmp_ctx, res);
90
91         if (res->count == 1) {
92                 oldMaxVersion = ldb_msg_find_uint64(res->msgs[0], "maxVersion", 0);
93         }
94
95         if (newMaxVersion == 0) {
96                 newMaxVersion = oldMaxVersion + 1;
97         } else {
98                 newMaxVersion = MAX(oldMaxVersion, newMaxVersion);
99         }
100
101         msg = ldb_msg_new(tmp_ctx);
102         if (!msg) goto failed;
103         msg->dn = dn;
104
105
106         ret = ldb_msg_add_empty(msg, "objectClass", LDB_FLAG_MOD_REPLACE);
107         if (ret != 0) goto failed;
108         ret = ldb_msg_add_string(msg, "objectClass", "winsMaxVersion");
109         if (ret != 0) goto failed;
110         ret = ldb_msg_add_empty(msg, "maxVersion", LDB_FLAG_MOD_REPLACE);
111         if (ret != 0) goto failed;
112         ret = ldb_msg_add_fmt(msg, "maxVersion", "%llu", (long long)newMaxVersion);
113         if (ret != 0) goto failed;
114
115         ret = ldb_modify(wins_db, msg);
116         if (ret != 0) ret = ldb_add(wins_db, msg);
117         if (ret != 0) goto failed;
118
119         trans = ldb_transaction_commit(wins_db);
120         if (trans != LDB_SUCCESS) goto failed;
121
122         talloc_free(tmp_ctx);
123         return newMaxVersion;
124
125 failed:
126         if (trans == LDB_SUCCESS) ldb_transaction_cancel(wins_db);
127         talloc_free(tmp_ctx);
128         return 0;
129 }
130
131 uint64_t winsdb_get_seqnumber(struct winsdb_handle *h)
132 {
133         int ret;
134         struct ldb_context *ldb = h->ldb;
135         struct ldb_dn *dn;
136         struct ldb_result *res = NULL;
137         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
138         uint64_t seqnumber = 0;
139
140         dn = ldb_dn_explode(tmp_ctx, "@BASEINFO");
141         if (!dn) goto failed;
142
143         /* find the record in the WINS database */
144         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, 
145                          NULL, NULL, &res);
146         if (ret != LDB_SUCCESS) goto failed;
147         talloc_steal(tmp_ctx, res);
148         if (res->count > 1) goto failed;
149
150         if (res->count == 1) {
151                 seqnumber = ldb_msg_find_uint64(res->msgs[0], "sequenceNumber", 0);
152         }
153
154 failed:
155         talloc_free(tmp_ctx);
156         return seqnumber;
157 }
158
159 /*
160   return a DN for a nbt_name
161 */
162 static struct ldb_dn *winsdb_dn(TALLOC_CTX *mem_ctx, struct nbt_name *name)
163 {
164         struct ldb_dn *dn;
165
166         dn = ldb_dn_string_compose(mem_ctx, NULL, "type=0x%02X", name->type);
167         if (dn && name->name && *name->name) {
168                 dn = ldb_dn_string_compose(mem_ctx, dn, "name=%s", name->name);
169         }
170         if (dn && name->scope && *name->scope) {
171                 dn = ldb_dn_string_compose(mem_ctx, dn, "scope=%s", name->scope);
172         }
173         return dn;
174 }
175
176 static NTSTATUS winsdb_nbt_name(TALLOC_CTX *mem_ctx, struct ldb_dn *dn, struct nbt_name **_name)
177 {
178         NTSTATUS status;
179         struct nbt_name *name;
180         uint32_t cur = 0;
181
182         name = talloc(mem_ctx, struct nbt_name);
183         if (!name) {
184                 status = NT_STATUS_NO_MEMORY;
185                 goto failed;
186         }
187
188         if (dn->comp_num > 3) {
189                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
190                 goto failed;
191         }
192
193         if (dn->comp_num > cur && strcasecmp("scope", dn->components[cur].name) == 0) {
194                 name->scope     = talloc_steal(name, dn->components[cur].value.data);
195                 cur++;
196         } else {
197                 name->scope     = NULL;
198         }
199
200         if (dn->comp_num > cur && strcasecmp("name", dn->components[cur].name) == 0) {
201                 name->name      = talloc_steal(name, dn->components[cur].value.data);
202                 cur++;
203         } else {
204                 name->name      = talloc_strdup(name, "");
205                 if (!name->name) {
206                         status = NT_STATUS_NO_MEMORY;
207                         goto failed;
208                 }
209         }
210
211         if (dn->comp_num > cur && strcasecmp("type", dn->components[cur].name) == 0) {
212                 name->type      = strtoul((char *)dn->components[cur].value.data, NULL, 0);
213                 cur++;
214         } else {
215                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
216                 goto failed;
217         }
218
219         *_name = name;
220         return NT_STATUS_OK;
221 failed:
222         talloc_free(name);
223         return status;
224 }
225
226 /*
227  decode the winsdb_addr("address") attribute:
228  "172.31.1.1" or 
229  "172.31.1.1;winsOwner:172.31.9.202;expireTime:20050923032330.0Z;"
230  are valid records
231 */
232 static NTSTATUS winsdb_addr_decode(struct winsdb_handle *h, struct winsdb_record *rec, struct ldb_val *val,
233                                    TALLOC_CTX *mem_ctx, struct winsdb_addr **_addr)
234 {
235         NTSTATUS status;
236         struct winsdb_addr *addr;
237         const char *address;
238         const char *wins_owner;
239         const char *expire_time;
240         char *p;
241
242         addr = talloc(mem_ctx, struct winsdb_addr);
243         if (!addr) {
244                 status = NT_STATUS_NO_MEMORY;
245                 goto failed;
246         }
247
248         address = (char *)val->data;
249
250         p = strchr(address, ';');
251         if (!p) {
252                 /* support old entries, with only the address */
253                 addr->address           = talloc_steal(addr, val->data);
254                 addr->wins_owner        = talloc_reference(addr, rec->wins_owner);
255                 if (!addr->wins_owner) {
256                         status = NT_STATUS_NO_MEMORY;
257                         goto failed;
258                 }
259                 addr->expire_time       = rec->expire_time;
260                 *_addr = addr;
261                 return NT_STATUS_OK;
262         }
263
264         *p = '\0';p++;
265         addr->address = talloc_strdup(addr, address);
266         if (!addr->address) {
267                 status = NT_STATUS_NO_MEMORY;
268                 goto failed;
269         }
270
271         if (strncmp("winsOwner:", p, 10) != 0) {
272                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
273                 goto failed;
274         }
275         wins_owner = p + 10;
276         p = strchr(wins_owner, ';');
277         if (!p) {
278                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
279                 goto failed;
280         }
281
282         *p = '\0';p++;
283         if (strcmp(wins_owner, "0.0.0.0") == 0) {
284                 wins_owner = h->local_owner;
285         }
286         addr->wins_owner = talloc_strdup(addr, wins_owner);
287         if (!addr->wins_owner) {
288                 status = NT_STATUS_NO_MEMORY;
289                 goto failed;
290         }
291
292         if (strncmp("expireTime:", p, 11) != 0) {
293                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
294                 goto failed;
295         }
296
297         expire_time = p + 11;
298         p = strchr(expire_time, ';');
299         if (!p) {
300                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
301                 goto failed;
302         }
303
304         *p = '\0';p++;
305         addr->expire_time = ldb_string_to_time(expire_time);
306
307         *_addr = addr;
308         return NT_STATUS_OK;
309 failed:
310         talloc_free(addr);
311         return status;
312 }
313
314 /*
315  encode the winsdb_addr("address") attribute like this:
316  non-static record:
317  "172.31.1.1;winsOwner:172.31.9.202;expireTime:20050923032330.0Z;"
318  static record:
319  "172.31.1.1"
320 */
321 static int ldb_msg_add_winsdb_addr(struct ldb_message *msg, struct winsdb_record *rec,
322                                    const char *attr_name, struct winsdb_addr *addr)
323 {
324         struct ldb_val val;
325         const char *str;
326
327         if (rec->is_static) {
328                 str = talloc_strdup(msg, addr->address);
329                 if (!str) return -1;
330         } else {
331                 char *expire_time;
332                 expire_time = ldb_timestring(msg, addr->expire_time);
333                 if (!expire_time) return -1;
334                 str = talloc_asprintf(msg, "%s;winsOwner:%s;expireTime:%s;",
335                                       addr->address, addr->wins_owner,
336                                       expire_time);
337                 talloc_free(expire_time);
338                 if (!str) return -1;
339         }
340
341         val.data = discard_const_p(uint8_t, str);
342         val.length = strlen(str);
343
344         return ldb_msg_add_value(msg, attr_name, &val);
345 }
346
347 struct winsdb_addr **winsdb_addr_list_make(TALLOC_CTX *mem_ctx)
348 {
349         struct winsdb_addr **addresses;
350
351         addresses = talloc_array(mem_ctx, struct winsdb_addr *, 1);
352         if (!addresses) return NULL;
353
354         addresses[0] = NULL;
355
356         return addresses;
357 }
358
359 static int winsdb_addr_sort_list (struct winsdb_addr **p1, struct winsdb_addr **p2, void *opaque)
360 {
361         struct winsdb_addr *a1 = talloc_get_type(*p1, struct winsdb_addr);
362         struct winsdb_addr *a2 = talloc_get_type(*p2, struct winsdb_addr);
363         struct winsdb_handle *h= talloc_get_type(opaque, struct winsdb_handle);
364         BOOL a1_owned = False;
365         BOOL a2_owned = False;
366
367         /*
368          * first the owned addresses with the newest to the oldest address
369          * then the replica addresses with the newest to the oldest address
370          */
371         if (a2->expire_time != a1->expire_time) {
372                 return a2->expire_time - a1->expire_time;
373         }
374
375         if (strcmp(a2->wins_owner, h->local_owner) == 0) {
376                 a2_owned = True;
377         }
378
379         if (strcmp(a1->wins_owner, h->local_owner) == 0) {
380                 a1_owned = True;
381         }
382
383         return a2_owned - a1_owned;
384 }
385
386 struct winsdb_addr **winsdb_addr_list_add(struct winsdb_handle *h, const struct winsdb_record *rec,
387                                           struct winsdb_addr **addresses, const char *address,
388                                           const char *wins_owner, time_t expire_time,
389                                           BOOL is_name_registration)
390 {
391         struct winsdb_addr *old_addr = NULL;
392         size_t len = 0;
393         size_t i;
394         BOOL found_old_replica = False;
395
396         /*
397          * count the addresses and maybe
398          * find an old entry for the new address
399          */
400         for (i=0; addresses[i]; i++) {
401                 if (old_addr) continue;
402                 if (strcmp(addresses[i]->address, address) == 0) {
403                         old_addr = addresses[i];
404                 }
405         }
406         len = i;
407
408         /*
409          * the address is already there
410          * and we can replace it
411          */
412         if (old_addr) {
413                 goto remove_old_addr;
414         }
415
416         /*
417          * if we don't have 25 addresses already,
418          * we can just add the new address
419          */
420         if (len < 25) {
421                 goto add_new_addr;
422         }
423
424         /*
425          * if we haven't found the address,
426          * and we have already have 25 addresses
427          * if so then we need to do the following:
428          * - if it isn't a name registration, then just ignore the new address
429          * - if it is a name registration, then first search for 
430          *   the oldest replica and if there's no replica address
431          *   search the oldest owned address
432          */
433         if (!is_name_registration) {
434                 return addresses;
435         }
436
437         /*
438          * find the oldest replica address, if there's no replica
439          * record at all, find the oldest owned address
440          */
441         for (i=0; addresses[i]; i++) {
442                 BOOL cur_is_replica = False;
443                 /* find out if the current address is a replica */
444                 if (strcmp(addresses[i]->wins_owner, h->local_owner) != 0) {
445                         cur_is_replica = True;
446                 }
447
448                 /*
449                  * if we already found a replica address and the current address
450                  * is not a replica, then skip it
451                  */
452                 if (found_old_replica && !cur_is_replica) continue;
453
454                 /*
455                  * if we found the first replica address, reset the address
456                  * that would be replaced
457                  */
458                 if (!found_old_replica && cur_is_replica) {
459                         found_old_replica = True;
460                         old_addr = addresses[i];
461                         continue;
462                 }
463
464                 /*
465                  * if the first address isn't a replica, just start with 
466                  * the first one
467                  */
468                 if (!old_addr) {
469                         old_addr = addresses[i];
470                         continue;
471                 }
472
473                 /*
474                  * see if we find an older address
475                  */
476                 if (addresses[i]->expire_time < old_addr->expire_time) {
477                         old_addr = addresses[i];
478                         continue;
479                 }
480         }
481
482 remove_old_addr:
483         winsdb_addr_list_remove(addresses, old_addr->address);
484         len --;
485
486 add_new_addr:
487         addresses = talloc_realloc(addresses, addresses, struct winsdb_addr *, len + 2);
488         if (!addresses) return NULL;
489
490         addresses[len] = talloc(addresses, struct winsdb_addr);
491         if (!addresses[len]) {
492                 talloc_free(addresses);
493                 return NULL;
494         }
495
496         addresses[len]->address = talloc_strdup(addresses[len], address);
497         if (!addresses[len]->address) {
498                 talloc_free(addresses);
499                 return NULL;
500         }
501
502         addresses[len]->wins_owner = talloc_strdup(addresses[len], wins_owner);
503         if (!addresses[len]->wins_owner) {
504                 talloc_free(addresses);
505                 return NULL;
506         }
507
508         addresses[len]->expire_time = expire_time;
509
510         addresses[len+1] = NULL;
511
512         ldb_qsort(addresses, len+1 , sizeof(addresses[0]), h, (ldb_qsort_cmp_fn_t)winsdb_addr_sort_list);
513
514         return addresses;
515 }
516
517 void winsdb_addr_list_remove(struct winsdb_addr **addresses, const char *address)
518 {
519         size_t i;
520
521         for (i=0; addresses[i]; i++) {
522                 if (strcmp(addresses[i]->address, address) == 0) {
523                         break;
524                 }
525         }
526
527         for (; addresses[i]; i++) {
528                 addresses[i] = addresses[i+1];
529         }
530
531         return;
532 }
533
534 struct winsdb_addr *winsdb_addr_list_check(struct winsdb_addr **addresses, const char *address)
535 {
536         size_t i;
537
538         for (i=0; addresses[i]; i++) {
539                 if (strcmp(addresses[i]->address, address) == 0) {
540                         return addresses[i];
541                 }
542         }
543
544         return NULL;
545 }
546
547 size_t winsdb_addr_list_length(struct winsdb_addr **addresses)
548 {
549         size_t i;
550         for (i=0; addresses[i]; i++);
551         return i;
552 }
553
554 const char **winsdb_addr_string_list(TALLOC_CTX *mem_ctx, struct winsdb_addr **addresses)
555 {
556         size_t len = winsdb_addr_list_length(addresses);
557         const char **str_list=NULL;
558         size_t i;
559
560         for (i=0; i < len; i++) {
561                 str_list = str_list_add(str_list, addresses[i]->address);
562                 if (!str_list[i]) {
563                         return NULL;
564                 }
565         }
566         talloc_steal(mem_ctx, str_list);
567         return str_list;
568 }
569
570 /*
571   load a WINS entry from the database
572 */
573 NTSTATUS winsdb_lookup(struct winsdb_handle *h, 
574                        struct nbt_name *name,
575                        TALLOC_CTX *mem_ctx,
576                        struct winsdb_record **_rec)
577 {
578         NTSTATUS status;
579         struct ldb_result *res = NULL;
580         int ret;
581         struct winsdb_record *rec;
582         struct ldb_context *wins_db = h->ldb;
583         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
584         time_t now = time(NULL);
585
586         /* find the record in the WINS database */
587         ret = ldb_search(wins_db, winsdb_dn(tmp_ctx, name), LDB_SCOPE_BASE, 
588                          NULL, NULL, &res);
589
590         if (ret != LDB_SUCCESS || res->count > 1) {
591                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
592                 goto failed;
593         } else if (res->count== 0) {
594                 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
595                 goto failed;
596         }
597
598         talloc_steal(tmp_ctx, res);
599
600         status = winsdb_record(h, res->msgs[0], tmp_ctx, now, &rec);
601         if (!NT_STATUS_IS_OK(status)) goto failed;
602
603         talloc_steal(mem_ctx, rec);
604         talloc_free(tmp_ctx);
605         *_rec = rec;
606         return NT_STATUS_OK;
607
608 failed:
609         talloc_free(tmp_ctx);
610         return status;
611 }
612
613 NTSTATUS winsdb_record(struct winsdb_handle *h, struct ldb_message *msg, TALLOC_CTX *mem_ctx, time_t now, struct winsdb_record **_rec)
614 {
615         NTSTATUS status;
616         struct winsdb_record *rec;
617         struct ldb_message_element *el;
618         struct nbt_name *name;
619         uint32_t i, j, num_values;
620
621         rec = talloc(mem_ctx, struct winsdb_record);
622         if (rec == NULL) {
623                 status = NT_STATUS_NO_MEMORY;
624                 goto failed;
625         }
626
627         status = winsdb_nbt_name(rec, msg->dn, &name);
628         if (!NT_STATUS_IS_OK(status)) goto failed;
629
630         if (strlen(name->name) > 15) {
631                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
632                 goto failed;
633         }
634         if (name->scope && strlen(name->scope) > 238) {
635                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
636                 goto failed;
637         }
638
639         /* parse it into a more convenient winsdb_record structure */
640         rec->name               = name;
641         rec->type               = ldb_msg_find_int(msg, "recordType", WREPL_TYPE_UNIQUE);
642         rec->state              = ldb_msg_find_int(msg, "recordState", WREPL_STATE_RELEASED);
643         rec->node               = ldb_msg_find_int(msg, "nodeType", WREPL_NODE_B);
644         rec->is_static          = ldb_msg_find_int(msg, "isStatic", 0);
645         rec->expire_time        = ldb_string_to_time(ldb_msg_find_string(msg, "expireTime", NULL));
646         rec->version            = ldb_msg_find_uint64(msg, "versionID", 0);
647         rec->wins_owner         = ldb_msg_find_string(msg, "winsOwner", NULL);
648         rec->registered_by      = ldb_msg_find_string(msg, "registeredBy", NULL);
649         talloc_steal(rec, rec->wins_owner);
650         talloc_steal(rec, rec->registered_by);
651
652         if (!rec->wins_owner || strcmp(rec->wins_owner, "0.0.0.0") == 0) {
653                 rec->wins_owner = h->local_owner;
654         }
655
656         el = ldb_msg_find_element(msg, "address");
657         if (el) {
658                 num_values = el->num_values;
659         } else {
660                 num_values = 0;
661         }
662
663         if (rec->type == WREPL_TYPE_UNIQUE || rec->type == WREPL_TYPE_GROUP) {
664                 if (num_values != 1) {
665                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
666                         goto failed;
667                 }
668         }
669         if (rec->state == WREPL_STATE_ACTIVE) {
670                 if (num_values < 1) {
671                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
672                         goto failed;
673                 }
674         }
675         if (num_values > 25) {
676                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
677                 goto failed;
678         }
679
680         /* see if it has already expired */
681         if (!rec->is_static &&
682             rec->expire_time <= now &&
683             rec->state == WREPL_STATE_ACTIVE) {
684                 DEBUG(5,("WINS: expiring name %s (expired at %s)\n", 
685                          nbt_name_string(mem_ctx, rec->name), timestring(mem_ctx, rec->expire_time)));
686                 rec->state = WREPL_STATE_RELEASED;
687         }
688
689         rec->addresses     = talloc_array(rec, struct winsdb_addr *, num_values+1);
690         if (rec->addresses == NULL) {
691                 status = NT_STATUS_NO_MEMORY;
692                 goto failed;
693         }
694
695         for (i=0,j=0;i<num_values;i++) {
696                 status = winsdb_addr_decode(h, rec, &el->values[i], rec->addresses, &rec->addresses[j]);
697                 if (!NT_STATUS_IS_OK(status)) goto failed;
698
699                 /*
700                  * the record isn't static and is active
701                  * then don't add the address if it's expired
702                  */
703                 if (!rec->is_static &&
704                     rec->addresses[j]->expire_time <= now &&
705                     rec->state == WREPL_STATE_ACTIVE) {
706                         DEBUG(5,("WINS: expiring name addr %s of %s (expired at %s)\n", 
707                                  rec->addresses[j]->address, nbt_name_string(rec->addresses[j], rec->name),
708                                  timestring(rec->addresses[j], rec->addresses[j]->expire_time)));
709                         talloc_free(rec->addresses[j]);
710                         rec->addresses[j] = NULL;
711                         continue;
712                 }
713                 j++;
714         }
715         rec->addresses[j] = NULL;
716         num_values = j;
717
718         if (rec->is_static && rec->state == WREPL_STATE_ACTIVE) {
719                 rec->expire_time = get_time_t_max();
720                 for (i=0;rec->addresses[i];i++) {
721                         rec->addresses[i]->expire_time = rec->expire_time;
722                 }
723         }
724
725         if (rec->state == WREPL_STATE_ACTIVE) {
726                 if (num_values < 1) {
727                         DEBUG(5,("WINS: expiring name %s (because it has no active addresses)\n", 
728                                  nbt_name_string(mem_ctx, rec->name)));
729                         rec->state = WREPL_STATE_RELEASED;
730                 }
731         }
732
733         *_rec = rec;
734         return NT_STATUS_OK;
735 failed:
736         if (NT_STATUS_EQUAL(NT_STATUS_INTERNAL_DB_CORRUPTION, status)) {
737                 DEBUG(1,("winsdb_record: corrupted record: %s\n", ldb_dn_linearize(rec, msg->dn)));
738         }
739         talloc_free(rec);
740         return status;
741 }
742
743 /*
744   form a ldb_message from a winsdb_record
745 */
746 struct ldb_message *winsdb_message(struct ldb_context *ldb, 
747                                    struct winsdb_record *rec, TALLOC_CTX *mem_ctx)
748 {
749         int i, ret=0;
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, 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);
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);
790         for (i=0;rec->addresses[i];i++) {
791                 ret |= ldb_msg_add_winsdb_addr(msg, rec, "address", rec->addresses[i]);
792         }
793         ret |= ldb_msg_add_empty(msg, "registeredBy", 0);
794         if (rec->registered_by) {
795                 ret |= ldb_msg_add_string(msg, "registeredBy", rec->registered_by);
796                 if (ret != 0) goto failed;
797         }
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 = 0;
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 != 0) 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);
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         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 != 0) 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);
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         const 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, rec->name);
912         if (dn == NULL) goto failed;
913
914         ret = ldb_delete(wins_db, dn);
915         if (ret != 0) 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);
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 winsdb_handle *h)
932 {
933         int trans;
934         int ret;
935         struct ldb_dn *dn;
936         struct ldb_result *res = NULL;
937         struct ldb_message *msg = NULL;
938         TALLOC_CTX *tmp_ctx = talloc_new(h);
939         unsigned int flags = 0;
940
941         trans = ldb_transaction_start(h->ldb);
942         if (trans != LDB_SUCCESS) goto failed;
943
944         /* check if we have a special @MODULES record already */
945         dn = ldb_dn_explode(tmp_ctx, "@MODULES");
946         if (!dn) goto failed;
947
948         /* find the record in the WINS database */
949         ret = ldb_search(h->ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res);
950         if (ret != LDB_SUCCESS) goto failed;
951         talloc_steal(tmp_ctx, res);
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 != 0) goto failed;
962
963         ret = ldb_add(h->ldb, msg);
964         if (ret != 0) 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 (lp_parm_bool(-1,"winsdb", "nosync", False)) {
975                 flags |= LDB_FLG_NOSYNC;
976         }
977
978         h->ldb = ldb_wrap_connect(h, lock_path(h, lp_wins_url()),
979                                   NULL, NULL, flags, NULL);
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, enum winsdb_handle_caller caller)
997 {
998         struct winsdb_handle *h = NULL;
999         const char *owner;
1000         unsigned int flags = 0;
1001         BOOL ret;
1002         int ldb_err;
1003
1004         h = talloc(mem_ctx, struct winsdb_handle);
1005         if (!h) return NULL;
1006
1007         if (lp_parm_bool(-1,"winsdb", "nosync", False)) {
1008                 flags |= LDB_FLG_NOSYNC;
1009         }
1010
1011         h->ldb = ldb_wrap_connect(h, lock_path(h, lp_wins_url()),
1012                                   NULL, NULL, flags, NULL);
1013         if (!h->ldb) goto failed;       
1014
1015         h->caller = caller;
1016
1017         owner = lp_parm_string(-1, "winsdb", "local_owner");
1018         if (!owner) {
1019                 owner = iface_n_ip(0);
1020         }
1021
1022         h->local_owner = talloc_strdup(h, owner);
1023         if (!h->local_owner) goto failed;
1024
1025         /* make sure the module list is available and used */
1026         ret = winsdb_check_or_add_module_list(h);
1027         if (!ret) goto failed;
1028
1029         ldb_err = ldb_set_opaque(h->ldb, "winsdb_handle", h);
1030         if (ldb_err != LDB_SUCCESS) goto failed;
1031
1032         return h;
1033 failed:
1034         talloc_free(h);
1035         return NULL;
1036 }