libsmb: Fix a typo
[metze/samba/wip.git] / source3 / libsmb / namequery.c
1 /*
2    Unix SMB/CIFS implementation.
3    name query routines
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Jeremy Allison 2007.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "../lib/util/tevent_ntstatus.h"
23 #include "libads/sitename_cache.h"
24 #include "../lib/addns/dnsquery.h"
25 #include "../libcli/netlogon/netlogon.h"
26 #include "lib/async_req/async_sock.h"
27 #include "lib/tsocket/tsocket.h"
28 #include "libsmb/nmblib.h"
29 #include "../libcli/nbt/libnbt.h"
30 #include "libads/kerberos_proto.h"
31
32 /* nmbd.c sets this to True. */
33 bool global_in_nmbd = False;
34
35 /****************************
36  * SERVER AFFINITY ROUTINES *
37  ****************************/
38
39  /* Server affinity is the concept of preferring the last domain
40     controller with whom you had a successful conversation */
41
42 /****************************************************************************
43 ****************************************************************************/
44 #define SAFKEY_FMT      "SAF/DOMAIN/%s"
45 #define SAF_TTL         900
46 #define SAFJOINKEY_FMT  "SAFJOIN/DOMAIN/%s"
47 #define SAFJOIN_TTL     3600
48
49 static char *saf_key(TALLOC_CTX *mem_ctx, const char *domain)
50 {
51         return talloc_asprintf_strupper_m(mem_ctx, SAFKEY_FMT, domain);
52 }
53
54 static char *saf_join_key(TALLOC_CTX *mem_ctx, const char *domain)
55 {
56         return talloc_asprintf_strupper_m(mem_ctx, SAFJOINKEY_FMT, domain);
57 }
58
59 /****************************************************************************
60 ****************************************************************************/
61
62 bool saf_store( const char *domain, const char *servername )
63 {
64         char *key;
65         time_t expire;
66         bool ret = False;
67
68         if ( !domain || !servername ) {
69                 DEBUG(2,("saf_store: "
70                         "Refusing to store empty domain or servername!\n"));
71                 return False;
72         }
73
74         if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
75                 DEBUG(0,("saf_store: "
76                         "refusing to store 0 length domain or servername!\n"));
77                 return False;
78         }
79
80         key = saf_key(talloc_tos(), domain);
81         if (key == NULL) {
82                 DEBUG(1, ("saf_key() failed\n"));
83                 return false;
84         }
85         expire = time( NULL ) + lp_parm_int(-1, "saf","ttl", SAF_TTL);
86
87         DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
88                 domain, servername, (unsigned int)expire ));
89
90         ret = gencache_set( key, servername, expire );
91
92         TALLOC_FREE( key );
93
94         return ret;
95 }
96
97 bool saf_join_store( const char *domain, const char *servername )
98 {
99         char *key;
100         time_t expire;
101         bool ret = False;
102
103         if ( !domain || !servername ) {
104                 DEBUG(2,("saf_join_store: Refusing to store empty domain or servername!\n"));
105                 return False;
106         }
107
108         if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
109                 DEBUG(0,("saf_join_store: refusing to store 0 length domain or servername!\n"));
110                 return False;
111         }
112
113         key = saf_join_key(talloc_tos(), domain);
114         if (key == NULL) {
115                 DEBUG(1, ("saf_join_key() failed\n"));
116                 return false;
117         }
118         expire = time( NULL ) + lp_parm_int(-1, "saf","join ttl", SAFJOIN_TTL);
119
120         DEBUG(10,("saf_join_store: domain = [%s], server = [%s], expire = [%u]\n",
121                 domain, servername, (unsigned int)expire ));
122
123         ret = gencache_set( key, servername, expire );
124
125         TALLOC_FREE( key );
126
127         return ret;
128 }
129
130 bool saf_delete( const char *domain )
131 {
132         char *key;
133         bool ret = False;
134
135         if ( !domain ) {
136                 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
137                 return False;
138         }
139
140         key = saf_join_key(talloc_tos(), domain);
141         if (key == NULL) {
142                 DEBUG(1, ("saf_join_key() failed\n"));
143                 return false;
144         }
145         ret = gencache_del(key);
146         TALLOC_FREE(key);
147
148         if (ret) {
149                 DEBUG(10,("saf_delete[join]: domain = [%s]\n", domain ));
150         }
151
152         key = saf_key(talloc_tos(), domain);
153         if (key == NULL) {
154                 DEBUG(1, ("saf_key() failed\n"));
155                 return false;
156         }
157         ret = gencache_del(key);
158         TALLOC_FREE(key);
159
160         if (ret) {
161                 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
162         }
163
164         return ret;
165 }
166
167 /****************************************************************************
168 ****************************************************************************/
169
170 char *saf_fetch(TALLOC_CTX *mem_ctx, const char *domain )
171 {
172         char *server = NULL;
173         time_t timeout;
174         bool ret = False;
175         char *key = NULL;
176
177         if ( !domain || strlen(domain) == 0) {
178                 DEBUG(2,("saf_fetch: Empty domain name!\n"));
179                 return NULL;
180         }
181
182         key = saf_join_key(talloc_tos(), domain);
183         if (key == NULL) {
184                 DEBUG(1, ("saf_join_key() failed\n"));
185                 return NULL;
186         }
187
188         ret = gencache_get( key, mem_ctx, &server, &timeout );
189
190         TALLOC_FREE( key );
191
192         if ( ret ) {
193                 DEBUG(5,("saf_fetch[join]: Returning \"%s\" for \"%s\" domain\n",
194                         server, domain ));
195                 return server;
196         }
197
198         key = saf_key(talloc_tos(), domain);
199         if (key == NULL) {
200                 DEBUG(1, ("saf_key() failed\n"));
201                 return NULL;
202         }
203
204         ret = gencache_get( key, mem_ctx, &server, &timeout );
205
206         TALLOC_FREE( key );
207
208         if ( !ret ) {
209                 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n",
210                                         domain ));
211         } else {
212                 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
213                         server, domain ));
214         }
215
216         return server;
217 }
218
219 static void set_socket_addr_v4(struct sockaddr_storage *addr)
220 {
221         if (!interpret_string_addr(addr, lp_nbt_client_socket_address(),
222                                    AI_NUMERICHOST|AI_PASSIVE)) {
223                 zero_sockaddr(addr);
224         }
225         if (addr->ss_family != AF_INET) {
226                 zero_sockaddr(addr);
227         }
228 }
229
230 static struct in_addr my_socket_addr_v4(void)
231 {
232         struct sockaddr_storage my_addr;
233         struct sockaddr_in *in_addr = (struct sockaddr_in *)((char *)&my_addr);
234
235         set_socket_addr_v4(&my_addr);
236         return in_addr->sin_addr;
237 }
238
239 /****************************************************************************
240  Generate a random trn_id.
241 ****************************************************************************/
242
243 static int generate_trn_id(void)
244 {
245         uint16_t id;
246
247         generate_random_buffer((uint8_t *)&id, sizeof(id));
248
249         return id % (unsigned)0x7FFF;
250 }
251
252 /****************************************************************************
253  Parse a node status response into an array of structures.
254 ****************************************************************************/
255
256 static struct node_status *parse_node_status(TALLOC_CTX *mem_ctx, char *p,
257                                 int *num_names,
258                                 struct node_status_extra *extra)
259 {
260         struct node_status *ret;
261         int i;
262
263         *num_names = CVAL(p,0);
264
265         if (*num_names == 0)
266                 return NULL;
267
268         ret = talloc_array(mem_ctx, struct node_status,*num_names);
269         if (!ret)
270                 return NULL;
271
272         p++;
273         for (i=0;i< *num_names;i++) {
274                 StrnCpy(ret[i].name,p,15);
275                 trim_char(ret[i].name,'\0',' ');
276                 ret[i].type = CVAL(p,15);
277                 ret[i].flags = p[16];
278                 p += 18;
279                 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
280                            ret[i].type, ret[i].flags));
281         }
282         /*
283          * Also, pick up the MAC address ...
284          */
285         if (extra) {
286                 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
287         }
288         return ret;
289 }
290
291 struct sock_packet_read_state {
292         struct tevent_context *ev;
293         enum packet_type type;
294         int trn_id;
295
296         struct nb_packet_reader *reader;
297         struct tevent_req *reader_req;
298
299         struct tdgram_context *sock;
300         struct tevent_req *socket_req;
301         uint8_t *buf;
302         struct tsocket_address *addr;
303
304         bool (*validator)(struct packet_struct *p,
305                           void *private_data);
306         void *private_data;
307
308         struct packet_struct *packet;
309 };
310
311 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s);
312 static void sock_packet_read_got_packet(struct tevent_req *subreq);
313 static void sock_packet_read_got_socket(struct tevent_req *subreq);
314
315 static struct tevent_req *sock_packet_read_send(
316         TALLOC_CTX *mem_ctx,
317         struct tevent_context *ev,
318         struct tdgram_context *sock,
319         struct nb_packet_reader *reader,
320         enum packet_type type,
321         int trn_id,
322         bool (*validator)(struct packet_struct *p, void *private_data),
323         void *private_data)
324 {
325         struct tevent_req *req;
326         struct sock_packet_read_state *state;
327
328         req = tevent_req_create(mem_ctx, &state,
329                                 struct sock_packet_read_state);
330         if (req == NULL) {
331                 return NULL;
332         }
333         talloc_set_destructor(state, sock_packet_read_state_destructor);
334         state->ev = ev;
335         state->reader = reader;
336         state->sock = sock;
337         state->type = type;
338         state->trn_id = trn_id;
339         state->validator = validator;
340         state->private_data = private_data;
341
342         if (reader != NULL) {
343                 state->reader_req = nb_packet_read_send(state, ev, reader);
344                 if (tevent_req_nomem(state->reader_req, req)) {
345                         return tevent_req_post(req, ev);
346                 }
347                 tevent_req_set_callback(
348                         state->reader_req, sock_packet_read_got_packet, req);
349         }
350
351         state->socket_req = tdgram_recvfrom_send(state, ev, state->sock);
352         if (tevent_req_nomem(state->socket_req, req)) {
353                 return tevent_req_post(req, ev);
354         }
355         tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
356                                 req);
357
358         return req;
359 }
360
361 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s)
362 {
363         if (s->packet != NULL) {
364                 free_packet(s->packet);
365                 s->packet = NULL;
366         }
367         return 0;
368 }
369
370 static void sock_packet_read_got_packet(struct tevent_req *subreq)
371 {
372         struct tevent_req *req = tevent_req_callback_data(
373                 subreq, struct tevent_req);
374         struct sock_packet_read_state *state = tevent_req_data(
375                 req, struct sock_packet_read_state);
376         NTSTATUS status;
377
378         status = nb_packet_read_recv(subreq, &state->packet);
379
380         TALLOC_FREE(state->reader_req);
381
382         if (!NT_STATUS_IS_OK(status)) {
383                 if (state->socket_req != NULL) {
384                         /*
385                          * Still waiting for socket
386                          */
387                         return;
388                 }
389                 /*
390                  * Both socket and packet reader failed
391                  */
392                 tevent_req_nterror(req, status);
393                 return;
394         }
395
396         if ((state->validator != NULL) &&
397             !state->validator(state->packet, state->private_data)) {
398                 DEBUG(10, ("validator failed\n"));
399
400                 free_packet(state->packet);
401                 state->packet = NULL;
402
403                 state->reader_req = nb_packet_read_send(state, state->ev,
404                                                         state->reader);
405                 if (tevent_req_nomem(state->reader_req, req)) {
406                         return;
407                 }
408                 tevent_req_set_callback(
409                         state->reader_req, sock_packet_read_got_packet, req);
410                 return;
411         }
412
413         TALLOC_FREE(state->socket_req);
414         tevent_req_done(req);
415 }
416
417 static void sock_packet_read_got_socket(struct tevent_req *subreq)
418 {
419         struct tevent_req *req = tevent_req_callback_data(
420                 subreq, struct tevent_req);
421         struct sock_packet_read_state *state = tevent_req_data(
422                 req, struct sock_packet_read_state);
423         union {
424                 struct sockaddr sa;
425                 struct sockaddr_in sin;
426         } addr;
427         ssize_t ret;
428         ssize_t received;
429         int err;
430         bool ok;
431
432         received = tdgram_recvfrom_recv(subreq, &err, state,
433                                         &state->buf, &state->addr);
434
435         TALLOC_FREE(state->socket_req);
436
437         if (received == -1) {
438                 if (state->reader_req != NULL) {
439                         /*
440                          * Still waiting for reader
441                          */
442                         return;
443                 }
444                 /*
445                  * Both socket and reader failed
446                  */
447                 tevent_req_nterror(req, map_nt_error_from_unix(err));
448                 return;
449         }
450         ok = tsocket_address_is_inet(state->addr, "ipv4");
451         if (!ok) {
452                 goto retry;
453         }
454         ret = tsocket_address_bsd_sockaddr(state->addr,
455                                            &addr.sa,
456                                            sizeof(addr.sin));
457         if (ret == -1) {
458                 tevent_req_nterror(req, map_nt_error_from_unix(errno));
459                 return;
460         }
461
462         state->packet = parse_packet((char *)state->buf, received, state->type,
463                                      addr.sin.sin_addr, addr.sin.sin_port);
464         if (state->packet == NULL) {
465                 DEBUG(10, ("parse_packet failed\n"));
466                 goto retry;
467         }
468         if ((state->trn_id != -1) &&
469             (state->trn_id != packet_trn_id(state->packet))) {
470                 DEBUG(10, ("Expected transaction id %d, got %d\n",
471                            state->trn_id, packet_trn_id(state->packet)));
472                 goto retry;
473         }
474
475         if ((state->validator != NULL) &&
476             !state->validator(state->packet, state->private_data)) {
477                 DEBUG(10, ("validator failed\n"));
478                 goto retry;
479         }
480
481         tevent_req_done(req);
482         return;
483
484 retry:
485         if (state->packet != NULL) {
486                 free_packet(state->packet);
487                 state->packet = NULL;
488         }
489         TALLOC_FREE(state->buf);
490         TALLOC_FREE(state->addr);
491
492         state->socket_req = tdgram_recvfrom_send(state, state->ev, state->sock);
493         if (tevent_req_nomem(state->socket_req, req)) {
494                 return;
495         }
496         tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
497                                 req);
498 }
499
500 static NTSTATUS sock_packet_read_recv(struct tevent_req *req,
501                                       struct packet_struct **ppacket)
502 {
503         struct sock_packet_read_state *state = tevent_req_data(
504                 req, struct sock_packet_read_state);
505         NTSTATUS status;
506
507         if (tevent_req_is_nterror(req, &status)) {
508                 return status;
509         }
510         *ppacket = state->packet;
511         state->packet = NULL;
512         return NT_STATUS_OK;
513 }
514
515 struct nb_trans_state {
516         struct tevent_context *ev;
517         struct tdgram_context *sock;
518         struct nb_packet_reader *reader;
519
520         struct tsocket_address *src_addr;
521         struct tsocket_address *dst_addr;
522         uint8_t *buf;
523         size_t buflen;
524         enum packet_type type;
525         int trn_id;
526
527         bool (*validator)(struct packet_struct *p,
528                           void *private_data);
529         void *private_data;
530
531         struct packet_struct *packet;
532 };
533
534 static int nb_trans_state_destructor(struct nb_trans_state *s);
535 static void nb_trans_got_reader(struct tevent_req *subreq);
536 static void nb_trans_done(struct tevent_req *subreq);
537 static void nb_trans_sent(struct tevent_req *subreq);
538 static void nb_trans_send_next(struct tevent_req *subreq);
539
540 static struct tevent_req *nb_trans_send(
541         TALLOC_CTX *mem_ctx,
542         struct tevent_context *ev,
543         const struct sockaddr_storage *_my_addr,
544         const struct sockaddr_storage *_dst_addr,
545         bool bcast,
546         uint8_t *buf, size_t buflen,
547         enum packet_type type, int trn_id,
548         bool (*validator)(struct packet_struct *p,
549                           void *private_data),
550         void *private_data)
551 {
552         const struct sockaddr *my_addr =
553                 discard_const_p(const struct sockaddr, _my_addr);
554         size_t my_addr_len = sizeof(*_my_addr);
555         const struct sockaddr *dst_addr =
556                 discard_const_p(const struct sockaddr, _dst_addr);
557         size_t dst_addr_len = sizeof(*_dst_addr);
558         struct tevent_req *req, *subreq;
559         struct nb_trans_state *state;
560         int ret;
561
562         req = tevent_req_create(mem_ctx, &state, struct nb_trans_state);
563         if (req == NULL) {
564                 return NULL;
565         }
566         talloc_set_destructor(state, nb_trans_state_destructor);
567         state->ev = ev;
568         state->buf = buf;
569         state->buflen = buflen;
570         state->type = type;
571         state->trn_id = trn_id;
572         state->validator = validator;
573         state->private_data = private_data;
574
575         ret = tsocket_address_bsd_from_sockaddr(state,
576                                                 my_addr, my_addr_len,
577                                                 &state->src_addr);
578         if (ret == -1) {
579                 tevent_req_nterror(req, map_nt_error_from_unix(errno));
580                 return tevent_req_post(req, ev);
581         }
582
583         ret = tsocket_address_bsd_from_sockaddr(state,
584                                                 dst_addr, dst_addr_len,
585                                                 &state->dst_addr);
586         if (ret == -1) {
587                 tevent_req_nterror(req, map_nt_error_from_unix(errno));
588                 return tevent_req_post(req, ev);
589         }
590
591         ret = tdgram_inet_udp_broadcast_socket(state->src_addr, state,
592                                                &state->sock);
593         if (ret == -1) {
594                 tevent_req_nterror(req, map_nt_error_from_unix(errno));
595                 return tevent_req_post(req, ev);
596         }
597
598         subreq = nb_packet_reader_send(state, ev, type, state->trn_id, NULL);
599         if (tevent_req_nomem(subreq, req)) {
600                 return tevent_req_post(req, ev);
601         }
602         tevent_req_set_callback(subreq, nb_trans_got_reader, req);
603         return req;
604 }
605
606 static int nb_trans_state_destructor(struct nb_trans_state *s)
607 {
608         if (s->packet != NULL) {
609                 free_packet(s->packet);
610                 s->packet = NULL;
611         }
612         return 0;
613 }
614
615 static void nb_trans_got_reader(struct tevent_req *subreq)
616 {
617         struct tevent_req *req = tevent_req_callback_data(
618                 subreq, struct tevent_req);
619         struct nb_trans_state *state = tevent_req_data(
620                 req, struct nb_trans_state);
621         NTSTATUS status;
622
623         status = nb_packet_reader_recv(subreq, state, &state->reader);
624         TALLOC_FREE(subreq);
625
626         if (!NT_STATUS_IS_OK(status)) {
627                 DEBUG(10, ("nmbd not around\n"));
628                 state->reader = NULL;
629         }
630
631         subreq = sock_packet_read_send(
632                 state, state->ev, state->sock,
633                 state->reader, state->type, state->trn_id,
634                 state->validator, state->private_data);
635         if (tevent_req_nomem(subreq, req)) {
636                 return;
637         }
638         tevent_req_set_callback(subreq, nb_trans_done, req);
639
640         subreq = tdgram_sendto_send(state, state->ev,
641                                     state->sock,
642                                     state->buf, state->buflen,
643                                     state->dst_addr);
644         if (tevent_req_nomem(subreq, req)) {
645                 return;
646         }
647         tevent_req_set_callback(subreq, nb_trans_sent, req);
648 }
649
650 static void nb_trans_sent(struct tevent_req *subreq)
651 {
652         struct tevent_req *req = tevent_req_callback_data(
653                 subreq, struct tevent_req);
654         struct nb_trans_state *state = tevent_req_data(
655                 req, struct nb_trans_state);
656         ssize_t sent;
657         int err;
658
659         sent = tdgram_sendto_recv(subreq, &err);
660         TALLOC_FREE(subreq);
661         if (sent == -1) {
662                 DEBUG(10, ("sendto failed: %s\n", strerror(err)));
663                 tevent_req_nterror(req, map_nt_error_from_unix(err));
664                 return;
665         }
666         subreq = tevent_wakeup_send(state, state->ev,
667                                     timeval_current_ofs(1, 0));
668         if (tevent_req_nomem(subreq, req)) {
669                 return;
670         }
671         tevent_req_set_callback(subreq, nb_trans_send_next, req);
672 }
673
674 static void nb_trans_send_next(struct tevent_req *subreq)
675 {
676         struct tevent_req *req = tevent_req_callback_data(
677                 subreq, struct tevent_req);
678         struct nb_trans_state *state = tevent_req_data(
679                 req, struct nb_trans_state);
680         bool ret;
681
682         ret = tevent_wakeup_recv(subreq);
683         TALLOC_FREE(subreq);
684         if (!ret) {
685                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
686                 return;
687         }
688         subreq = tdgram_sendto_send(state, state->ev,
689                                     state->sock,
690                                     state->buf, state->buflen,
691                                     state->dst_addr);
692         if (tevent_req_nomem(subreq, req)) {
693                 return;
694         }
695         tevent_req_set_callback(subreq, nb_trans_sent, req);
696 }
697
698 static void nb_trans_done(struct tevent_req *subreq)
699 {
700         struct tevent_req *req = tevent_req_callback_data(
701                 subreq, struct tevent_req);
702         struct nb_trans_state *state = tevent_req_data(
703                 req, struct nb_trans_state);
704         NTSTATUS status;
705
706         status = sock_packet_read_recv(subreq, &state->packet);
707         TALLOC_FREE(subreq);
708         if (tevent_req_nterror(req, status)) {
709                 return;
710         }
711         tevent_req_done(req);
712 }
713
714 static NTSTATUS nb_trans_recv(struct tevent_req *req,
715                               struct packet_struct **ppacket)
716 {
717         struct nb_trans_state *state = tevent_req_data(
718                 req, struct nb_trans_state);
719         NTSTATUS status;
720
721         if (tevent_req_is_nterror(req, &status)) {
722                 return status;
723         }
724         *ppacket = state->packet;
725         state->packet = NULL;
726         return NT_STATUS_OK;
727 }
728
729 /****************************************************************************
730  Do a NBT node status query on an open socket and return an array of
731  structures holding the returned names or NULL if the query failed.
732 **************************************************************************/
733
734 struct node_status_query_state {
735         struct sockaddr_storage my_addr;
736         struct sockaddr_storage addr;
737         uint8_t buf[1024];
738         ssize_t buflen;
739         struct packet_struct *packet;
740 };
741
742 static int node_status_query_state_destructor(
743         struct node_status_query_state *s);
744 static bool node_status_query_validator(struct packet_struct *p,
745                                         void *private_data);
746 static void node_status_query_done(struct tevent_req *subreq);
747
748 struct tevent_req *node_status_query_send(TALLOC_CTX *mem_ctx,
749                                           struct tevent_context *ev,
750                                           struct nmb_name *name,
751                                           const struct sockaddr_storage *addr)
752 {
753         struct tevent_req *req, *subreq;
754         struct node_status_query_state *state;
755         struct packet_struct p;
756         struct nmb_packet *nmb = &p.packet.nmb;
757         struct sockaddr_in *in_addr;
758
759         req = tevent_req_create(mem_ctx, &state,
760                                 struct node_status_query_state);
761         if (req == NULL) {
762                 return NULL;
763         }
764         talloc_set_destructor(state, node_status_query_state_destructor);
765
766         if (addr->ss_family != AF_INET) {
767                 /* Can't do node status to IPv6 */
768                 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
769                 return tevent_req_post(req, ev);
770         }
771
772         state->addr = *addr;
773         in_addr = (struct sockaddr_in *)(void *)&state->addr;
774         in_addr->sin_port = htons(NMB_PORT);
775
776         set_socket_addr_v4(&state->my_addr);
777
778         ZERO_STRUCT(p);
779         nmb->header.name_trn_id = generate_trn_id();
780         nmb->header.opcode = 0;
781         nmb->header.response = false;
782         nmb->header.nm_flags.bcast = false;
783         nmb->header.nm_flags.recursion_available = false;
784         nmb->header.nm_flags.recursion_desired = false;
785         nmb->header.nm_flags.trunc = false;
786         nmb->header.nm_flags.authoritative = false;
787         nmb->header.rcode = 0;
788         nmb->header.qdcount = 1;
789         nmb->header.ancount = 0;
790         nmb->header.nscount = 0;
791         nmb->header.arcount = 0;
792         nmb->question.question_name = *name;
793         nmb->question.question_type = 0x21;
794         nmb->question.question_class = 0x1;
795
796         state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
797                                      &p);
798         if (state->buflen == 0) {
799                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
800                 DEBUG(10, ("build_packet failed\n"));
801                 return tevent_req_post(req, ev);
802         }
803
804         subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, false,
805                                state->buf, state->buflen,
806                                NMB_PACKET, nmb->header.name_trn_id,
807                                node_status_query_validator, NULL);
808         if (tevent_req_nomem(subreq, req)) {
809                 DEBUG(10, ("nb_trans_send failed\n"));
810                 return tevent_req_post(req, ev);
811         }
812         if (!tevent_req_set_endtime(req, ev, timeval_current_ofs(10, 0))) {
813                 return tevent_req_post(req, ev);
814         }
815         tevent_req_set_callback(subreq, node_status_query_done, req);
816         return req;
817 }
818
819 static bool node_status_query_validator(struct packet_struct *p,
820                                         void *private_data)
821 {
822         struct nmb_packet *nmb = &p->packet.nmb;
823         debug_nmb_packet(p);
824
825         if (nmb->header.opcode != 0 ||
826             nmb->header.nm_flags.bcast ||
827             nmb->header.rcode ||
828             !nmb->header.ancount ||
829             nmb->answers->rr_type != 0x21) {
830                 /*
831                  * XXXX what do we do with this? could be a redirect,
832                  * but we'll discard it for the moment
833                  */
834                 return false;
835         }
836         return true;
837 }
838
839 static int node_status_query_state_destructor(
840         struct node_status_query_state *s)
841 {
842         if (s->packet != NULL) {
843                 free_packet(s->packet);
844                 s->packet = NULL;
845         }
846         return 0;
847 }
848
849 static void node_status_query_done(struct tevent_req *subreq)
850 {
851         struct tevent_req *req = tevent_req_callback_data(
852                 subreq, struct tevent_req);
853         struct node_status_query_state *state = tevent_req_data(
854                 req, struct node_status_query_state);
855         NTSTATUS status;
856
857         status = nb_trans_recv(subreq, &state->packet);
858         TALLOC_FREE(subreq);
859         if (tevent_req_nterror(req, status)) {
860                 return;
861         }
862         tevent_req_done(req);
863 }
864
865 NTSTATUS node_status_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
866                                 struct node_status **pnode_status,
867                                 int *pnum_names,
868                                 struct node_status_extra *extra)
869 {
870         struct node_status_query_state *state = tevent_req_data(
871                 req, struct node_status_query_state);
872         struct node_status *node_status;
873         int num_names;
874         NTSTATUS status;
875
876         if (tevent_req_is_nterror(req, &status)) {
877                 return status;
878         }
879         node_status = parse_node_status(
880                 mem_ctx, &state->packet->packet.nmb.answers->rdata[0],
881                 &num_names, extra);
882         if (node_status == NULL) {
883                 return NT_STATUS_NO_MEMORY;
884         }
885         *pnode_status = node_status;
886         *pnum_names = num_names;
887         return NT_STATUS_OK;
888 }
889
890 NTSTATUS node_status_query(TALLOC_CTX *mem_ctx, struct nmb_name *name,
891                            const struct sockaddr_storage *addr,
892                            struct node_status **pnode_status,
893                            int *pnum_names,
894                            struct node_status_extra *extra)
895 {
896         TALLOC_CTX *frame = talloc_stackframe();
897         struct tevent_context *ev;
898         struct tevent_req *req;
899         NTSTATUS status = NT_STATUS_NO_MEMORY;
900
901         ev = samba_tevent_context_init(frame);
902         if (ev == NULL) {
903                 goto fail;
904         }
905         req = node_status_query_send(ev, ev, name, addr);
906         if (req == NULL) {
907                 goto fail;
908         }
909         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
910                 goto fail;
911         }
912         status = node_status_query_recv(req, mem_ctx, pnode_status,
913                                         pnum_names, extra);
914  fail:
915         TALLOC_FREE(frame);
916         return status;
917 }
918
919 static bool name_status_lmhosts(const struct sockaddr_storage *paddr,
920                                 int qname_type, fstring pname)
921 {
922         FILE *f;
923         char *name;
924         int name_type;
925         struct sockaddr_storage addr;
926
927         if (paddr->ss_family != AF_INET) {
928                 return false;
929         }
930
931         f = startlmhosts(get_dyn_LMHOSTSFILE());
932         if (f == NULL) {
933                 return false;
934         }
935
936         while (getlmhostsent(talloc_tos(), f, &name, &name_type, &addr)) {
937                 if (addr.ss_family != AF_INET) {
938                         continue;
939                 }
940                 if (name_type != qname_type) {
941                         continue;
942                 }
943                 if (memcmp(&((const struct sockaddr_in *)paddr)->sin_addr,
944                            &((const struct sockaddr_in *)&addr)->sin_addr,
945                            sizeof(struct in_addr)) == 0) {
946                         fstrcpy(pname, name);
947                         endlmhosts(f);
948                         return true;
949                 }
950         }
951         endlmhosts(f);
952         return false;
953 }
954
955 /****************************************************************************
956  Find the first type XX name in a node status reply - used for finding
957  a servers name given its IP. Return the matched name in *name.
958 **************************************************************************/
959
960 bool name_status_find(const char *q_name,
961                         int q_type,
962                         int type,
963                         const struct sockaddr_storage *to_ss,
964                         fstring name)
965 {
966         char addr[INET6_ADDRSTRLEN];
967         struct sockaddr_storage ss;
968         struct node_status *addrs = NULL;
969         struct nmb_name nname;
970         int count, i;
971         bool result = false;
972         NTSTATUS status;
973
974         if (lp_disable_netbios()) {
975                 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
976                                         q_name, q_type));
977                 return False;
978         }
979
980         print_sockaddr(addr, sizeof(addr), to_ss);
981
982         DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
983                    q_type, addr));
984
985         /* Check the cache first. */
986
987         if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
988                 return True;
989         }
990
991         if (to_ss->ss_family != AF_INET) {
992                 /* Can't do node status to IPv6 */
993                 return false;
994         }
995
996         result = name_status_lmhosts(to_ss, type, name);
997         if (result) {
998                 DBG_DEBUG("Found name %s in lmhosts\n", name);
999                 namecache_status_store(q_name, q_type, type, to_ss, name);
1000                 return true;
1001         }
1002
1003         set_socket_addr_v4(&ss);
1004
1005         /* W2K PDC's seem not to respond to '*'#0. JRA */
1006         make_nmb_name(&nname, q_name, q_type);
1007         status = node_status_query(talloc_tos(), &nname, to_ss,
1008                                    &addrs, &count, NULL);
1009         if (!NT_STATUS_IS_OK(status)) {
1010                 goto done;
1011         }
1012
1013         for (i=0;i<count;i++) {
1014                 /* Find first one of the requested type that's not a GROUP. */
1015                 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
1016                         break;
1017         }
1018         if (i == count)
1019                 goto done;
1020
1021         pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
1022
1023         /* Store the result in the cache. */
1024         /* but don't store an entry for 0x1c names here.  Here we have
1025            a single host and DOMAIN<0x1c> names should be a list of hosts */
1026
1027         if ( q_type != 0x1c ) {
1028                 namecache_status_store(q_name, q_type, type, to_ss, name);
1029         }
1030
1031         result = true;
1032
1033  done:
1034         TALLOC_FREE(addrs);
1035
1036         DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
1037
1038         if (result)
1039                 DEBUGADD(10, (", name %s ip address is %s", name, addr));
1040
1041         DEBUG(10, ("\n"));
1042
1043         return result;
1044 }
1045
1046 /*
1047   comparison function used by sort_addr_list
1048 */
1049
1050 static int addr_compare(const struct sockaddr_storage *ss1,
1051                         const struct sockaddr_storage *ss2)
1052 {
1053         int max_bits1=0, max_bits2=0;
1054         int num_interfaces = iface_count();
1055         int i;
1056
1057         /* Sort IPv4 addresses first. */
1058         if (ss1->ss_family != ss2->ss_family) {
1059                 if (ss2->ss_family == AF_INET) {
1060                         return 1;
1061                 } else {
1062                         return -1;
1063                 }
1064         }
1065
1066         /* Here we know both addresses are of the same
1067          * family. */
1068
1069         for (i=0;i<num_interfaces;i++) {
1070                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1071                 const unsigned char *p_ss1 = NULL;
1072                 const unsigned char *p_ss2 = NULL;
1073                 const unsigned char *p_if = NULL;
1074                 size_t len = 0;
1075                 int bits1, bits2;
1076
1077                 if (pss->ss_family != ss1->ss_family) {
1078                         /* Ignore interfaces of the wrong type. */
1079                         continue;
1080                 }
1081                 if (pss->ss_family == AF_INET) {
1082                         p_if = (const unsigned char *)
1083                                 &((const struct sockaddr_in *)pss)->sin_addr;
1084                         p_ss1 = (const unsigned char *)
1085                                 &((const struct sockaddr_in *)ss1)->sin_addr;
1086                         p_ss2 = (const unsigned char *)
1087                                 &((const struct sockaddr_in *)ss2)->sin_addr;
1088                         len = 4;
1089                 }
1090 #if defined(HAVE_IPV6)
1091                 if (pss->ss_family == AF_INET6) {
1092                         p_if = (const unsigned char *)
1093                                 &((const struct sockaddr_in6 *)pss)->sin6_addr;
1094                         p_ss1 = (const unsigned char *)
1095                                 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
1096                         p_ss2 = (const unsigned char *)
1097                                 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
1098                         len = 16;
1099                 }
1100 #endif
1101                 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
1102                         continue;
1103                 }
1104                 bits1 = matching_len_bits(p_ss1, p_if, len);
1105                 bits2 = matching_len_bits(p_ss2, p_if, len);
1106                 max_bits1 = MAX(bits1, max_bits1);
1107                 max_bits2 = MAX(bits2, max_bits2);
1108         }
1109
1110         /* Bias towards directly reachable IPs */
1111         if (iface_local((const struct sockaddr *)ss1)) {
1112                 if (ss1->ss_family == AF_INET) {
1113                         max_bits1 += 32;
1114                 } else {
1115                         max_bits1 += 128;
1116                 }
1117         }
1118         if (iface_local((const struct sockaddr *)ss2)) {
1119                 if (ss2->ss_family == AF_INET) {
1120                         max_bits2 += 32;
1121                 } else {
1122                         max_bits2 += 128;
1123                 }
1124         }
1125         return max_bits2 - max_bits1;
1126 }
1127
1128 /*******************************************************************
1129  compare 2 ldap IPs by nearness to our interfaces - used in qsort
1130 *******************************************************************/
1131
1132 static int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
1133 {
1134         int result;
1135
1136         if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
1137                 return result;
1138         }
1139
1140         if (ss1->port > ss2->port) {
1141                 return 1;
1142         }
1143
1144         if (ss1->port < ss2->port) {
1145                 return -1;
1146         }
1147
1148         return 0;
1149 }
1150
1151 /*
1152   sort an IP list so that names that are close to one of our interfaces
1153   are at the top. This prevents the problem where a WINS server returns an IP
1154   that is not reachable from our subnet as the first match
1155 */
1156
1157 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
1158 {
1159         if (count <= 1) {
1160                 return;
1161         }
1162
1163         TYPESAFE_QSORT(sslist, count, addr_compare);
1164 }
1165
1166 static void sort_service_list(struct ip_service *servlist, int count)
1167 {
1168         if (count <= 1) {
1169                 return;
1170         }
1171
1172         TYPESAFE_QSORT(servlist, count, ip_service_compare);
1173 }
1174
1175 /**********************************************************************
1176  Remove any duplicate address/port pairs in the list
1177  *********************************************************************/
1178
1179 int remove_duplicate_addrs2(struct ip_service *iplist, int count )
1180 {
1181         int i, j;
1182
1183         DEBUG(10,("remove_duplicate_addrs2: "
1184                         "looking for duplicate address/port pairs\n"));
1185
1186         /* One loop to set duplicates to a zero addr. */
1187         for ( i=0; i<count; i++ ) {
1188                 if ( is_zero_addr(&iplist[i].ss)) {
1189                         continue;
1190                 }
1191
1192                 for ( j=i+1; j<count; j++ ) {
1193                         if (sockaddr_equal((struct sockaddr *)(void *)&iplist[i].ss,
1194                                            (struct sockaddr *)(void *)&iplist[j].ss) &&
1195                                         iplist[i].port == iplist[j].port) {
1196                                 zero_sockaddr(&iplist[j].ss);
1197                         }
1198                 }
1199         }
1200
1201         /* Now remove any addresses set to zero above. */
1202         for (i = 0; i < count; i++) {
1203                 while (i < count &&
1204                                 is_zero_addr(&iplist[i].ss)) {
1205                         if (count-i-1>0) {
1206                                 memmove(&iplist[i],
1207                                         &iplist[i+1],
1208                                         (count-i-1)*sizeof(struct ip_service));
1209                         }
1210                         count--;
1211                 }
1212         }
1213
1214         return count;
1215 }
1216
1217 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1218 {
1219         TALLOC_CTX *frame = talloc_stackframe();
1220         struct ip_service *iplist_new = talloc_array(frame, struct ip_service, count);
1221         int i, j;
1222
1223         if (iplist_new == NULL) {
1224                 TALLOC_FREE(frame);
1225                 return false;
1226         }
1227
1228         j = 0;
1229
1230         /* Copy IPv4 first. */
1231         for (i = 0; i < count; i++) {
1232                 if (iplist[i].ss.ss_family == AF_INET) {
1233                         iplist_new[j++] = iplist[i];
1234                 }
1235         }
1236
1237         /* Copy IPv6. */
1238         for (i = 0; i < count; i++) {
1239                 if (iplist[i].ss.ss_family != AF_INET) {
1240                         iplist_new[j++] = iplist[i];
1241                 }
1242         }
1243
1244         memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1245         TALLOC_FREE(frame);
1246         return true;
1247 }
1248
1249 /****************************************************************************
1250  Do a netbios name query to find someones IP.
1251  Returns an array of IP addresses or NULL if none.
1252  *count will be set to the number of addresses returned.
1253  *timed_out is set if we failed by timing out
1254 ****************************************************************************/
1255
1256 struct name_query_state {
1257         struct sockaddr_storage my_addr;
1258         struct sockaddr_storage addr;
1259         bool bcast;
1260
1261
1262         uint8_t buf[1024];
1263         ssize_t buflen;
1264
1265         NTSTATUS validate_error;
1266         uint8_t flags;
1267
1268         struct sockaddr_storage *addrs;
1269         int num_addrs;
1270 };
1271
1272 static bool name_query_validator(struct packet_struct *p, void *private_data);
1273 static void name_query_done(struct tevent_req *subreq);
1274
1275 struct tevent_req *name_query_send(TALLOC_CTX *mem_ctx,
1276                                    struct tevent_context *ev,
1277                                    const char *name, int name_type,
1278                                    bool bcast, bool recurse,
1279                                    const struct sockaddr_storage *addr)
1280 {
1281         struct tevent_req *req, *subreq;
1282         struct name_query_state *state;
1283         struct packet_struct p;
1284         struct nmb_packet *nmb = &p.packet.nmb;
1285         struct sockaddr_in *in_addr;
1286
1287         req = tevent_req_create(mem_ctx, &state, struct name_query_state);
1288         if (req == NULL) {
1289                 return NULL;
1290         }
1291         state->bcast = bcast;
1292
1293         if (addr->ss_family != AF_INET) {
1294                 /* Can't do node status to IPv6 */
1295                 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1296                 return tevent_req_post(req, ev);
1297         }
1298
1299         if (lp_disable_netbios()) {
1300                 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1301                                         name, name_type));
1302                 tevent_req_nterror(req, NT_STATUS_NOT_SUPPORTED);
1303                 return tevent_req_post(req, ev);
1304         }
1305
1306         state->addr = *addr;
1307         in_addr = (struct sockaddr_in *)(void *)&state->addr;
1308         in_addr->sin_port = htons(NMB_PORT);
1309
1310         set_socket_addr_v4(&state->my_addr);
1311
1312         ZERO_STRUCT(p);
1313         nmb->header.name_trn_id = generate_trn_id();
1314         nmb->header.opcode = 0;
1315         nmb->header.response = false;
1316         nmb->header.nm_flags.bcast = bcast;
1317         nmb->header.nm_flags.recursion_available = false;
1318         nmb->header.nm_flags.recursion_desired = recurse;
1319         nmb->header.nm_flags.trunc = false;
1320         nmb->header.nm_flags.authoritative = false;
1321         nmb->header.rcode = 0;
1322         nmb->header.qdcount = 1;
1323         nmb->header.ancount = 0;
1324         nmb->header.nscount = 0;
1325         nmb->header.arcount = 0;
1326
1327         make_nmb_name(&nmb->question.question_name,name,name_type);
1328
1329         nmb->question.question_type = 0x20;
1330         nmb->question.question_class = 0x1;
1331
1332         state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
1333                                      &p);
1334         if (state->buflen == 0) {
1335                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1336                 DEBUG(10, ("build_packet failed\n"));
1337                 return tevent_req_post(req, ev);
1338         }
1339
1340         subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, bcast,
1341                                state->buf, state->buflen,
1342                                NMB_PACKET, nmb->header.name_trn_id,
1343                                name_query_validator, state);
1344         if (tevent_req_nomem(subreq, req)) {
1345                 DEBUG(10, ("nb_trans_send failed\n"));
1346                 return tevent_req_post(req, ev);
1347         }
1348         tevent_req_set_callback(subreq, name_query_done, req);
1349         return req;
1350 }
1351
1352 static bool name_query_validator(struct packet_struct *p, void *private_data)
1353 {
1354         struct name_query_state *state = talloc_get_type_abort(
1355                 private_data, struct name_query_state);
1356         struct nmb_packet *nmb = &p->packet.nmb;
1357         struct sockaddr_storage *tmp_addrs;
1358         bool got_unique_netbios_name = false;
1359         int i;
1360
1361         debug_nmb_packet(p);
1362
1363         /*
1364          * If we get a Negative Name Query Response from a WINS
1365          * server, we should report it and give up.
1366          */
1367         if( 0 == nmb->header.opcode     /* A query response   */
1368             && !state->bcast            /* from a WINS server */
1369             && nmb->header.rcode        /* Error returned     */
1370                 ) {
1371
1372                 if( DEBUGLVL( 3 ) ) {
1373                         /* Only executed if DEBUGLEVEL >= 3 */
1374                         dbgtext( "Negative name query "
1375                                  "response, rcode 0x%02x: ",
1376                                  nmb->header.rcode );
1377                         switch( nmb->header.rcode ) {
1378                         case 0x01:
1379                                 dbgtext("Request was invalidly formatted.\n");
1380                                 break;
1381                         case 0x02:
1382                                 dbgtext("Problem with NBNS, cannot process "
1383                                         "name.\n");
1384                                 break;
1385                         case 0x03:
1386                                 dbgtext("The name requested does not "
1387                                         "exist.\n");
1388                                 break;
1389                         case 0x04:
1390                                 dbgtext("Unsupported request error.\n");
1391                                 break;
1392                         case 0x05:
1393                                 dbgtext("Query refused error.\n");
1394                                 break;
1395                         default:
1396                                 dbgtext("Unrecognized error code.\n" );
1397                                 break;
1398                         }
1399                 }
1400
1401                 /*
1402                  * We accept this packet as valid, but tell the upper
1403                  * layers that it's a negative response.
1404                  */
1405                 state->validate_error = NT_STATUS_NOT_FOUND;
1406                 return true;
1407         }
1408
1409         if (nmb->header.opcode != 0 ||
1410             nmb->header.nm_flags.bcast ||
1411             nmb->header.rcode ||
1412             !nmb->header.ancount) {
1413                 /*
1414                  * XXXX what do we do with this? Could be a redirect,
1415                  * but we'll discard it for the moment.
1416                  */
1417                 return false;
1418         }
1419
1420         tmp_addrs = talloc_realloc(
1421                 state, state->addrs, struct sockaddr_storage,
1422                 state->num_addrs + nmb->answers->rdlength/6);
1423         if (tmp_addrs == NULL) {
1424                 state->validate_error = NT_STATUS_NO_MEMORY;
1425                 return true;
1426         }
1427         state->addrs = tmp_addrs;
1428
1429         DEBUG(2,("Got a positive name query response "
1430                  "from %s ( ", inet_ntoa(p->ip)));
1431
1432         for (i=0; i<nmb->answers->rdlength/6; i++) {
1433                 uint16_t flags;
1434                 struct in_addr ip;
1435                 struct sockaddr_storage addr;
1436                 int j;
1437
1438                 flags = RSVAL(&nmb->answers->rdata[i*6], 0);
1439                 got_unique_netbios_name |= ((flags & 0x8000) == 0);
1440
1441                 putip((char *)&ip,&nmb->answers->rdata[2+i*6]);
1442                 in_addr_to_sockaddr_storage(&addr, ip);
1443
1444                 if (is_zero_addr(&addr)) {
1445                         continue;
1446                 }
1447
1448                 for (j=0; j<state->num_addrs; j++) {
1449                         if (sockaddr_equal(
1450                                     (struct sockaddr *)(void *)&addr,
1451                                     (struct sockaddr *)(void *)&state->addrs[j])) {
1452                                 break;
1453                         }
1454                 }
1455                 if (j < state->num_addrs) {
1456                         /* Already got it */
1457                         continue;
1458                 }
1459
1460                 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1461
1462                 state->addrs[state->num_addrs] = addr;
1463                 state->num_addrs += 1;
1464         }
1465         DEBUGADD(2,(")\n"));
1466
1467         /* We add the flags back ... */
1468         if (nmb->header.response)
1469                 state->flags |= NM_FLAGS_RS;
1470         if (nmb->header.nm_flags.authoritative)
1471                 state->flags |= NM_FLAGS_AA;
1472         if (nmb->header.nm_flags.trunc)
1473                 state->flags |= NM_FLAGS_TC;
1474         if (nmb->header.nm_flags.recursion_desired)
1475                 state->flags |= NM_FLAGS_RD;
1476         if (nmb->header.nm_flags.recursion_available)
1477                 state->flags |= NM_FLAGS_RA;
1478         if (nmb->header.nm_flags.bcast)
1479                 state->flags |= NM_FLAGS_B;
1480
1481         if (state->bcast) {
1482                 /*
1483                  * We have to collect all entries coming in from broadcast
1484                  * queries. If we got a unique name, we're done.
1485                  */
1486                 return got_unique_netbios_name;
1487         }
1488         /*
1489          * WINS responses are accepted when they are received
1490          */
1491         return true;
1492 }
1493
1494 static void name_query_done(struct tevent_req *subreq)
1495 {
1496         struct tevent_req *req = tevent_req_callback_data(
1497                 subreq, struct tevent_req);
1498         struct name_query_state *state = tevent_req_data(
1499                 req, struct name_query_state);
1500         NTSTATUS status;
1501         struct packet_struct *p = NULL;
1502
1503         status = nb_trans_recv(subreq, &p);
1504         TALLOC_FREE(subreq);
1505         if (tevent_req_nterror(req, status)) {
1506                 return;
1507         }
1508         if (!NT_STATUS_IS_OK(state->validate_error)) {
1509                 tevent_req_nterror(req, state->validate_error);
1510                 return;
1511         }
1512         if (p != NULL) {
1513                 /*
1514                  * Free the packet here, we've collected the response in the
1515                  * validator
1516                  */
1517                 free_packet(p);
1518         }
1519         tevent_req_done(req);
1520 }
1521
1522 NTSTATUS name_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1523                          struct sockaddr_storage **addrs, int *num_addrs,
1524                          uint8_t *flags)
1525 {
1526         struct name_query_state *state = tevent_req_data(
1527                 req, struct name_query_state);
1528         NTSTATUS status;
1529
1530         if (tevent_req_is_nterror(req, &status)) {
1531                 if (state->bcast &&
1532                     NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
1533                         /*
1534                          * In the broadcast case we collect replies until the
1535                          * timeout.
1536                          */
1537                         status = NT_STATUS_OK;
1538                 }
1539                 if (!NT_STATUS_IS_OK(status)) {
1540                         return status;
1541                 }
1542         }
1543         if (state->num_addrs == 0) {
1544                 return NT_STATUS_NOT_FOUND;
1545         }
1546         *addrs = talloc_move(mem_ctx, &state->addrs);
1547         sort_addr_list(*addrs, state->num_addrs);
1548         *num_addrs = state->num_addrs;
1549         if (flags != NULL) {
1550                 *flags = state->flags;
1551         }
1552         return NT_STATUS_OK;
1553 }
1554
1555 NTSTATUS name_query(const char *name, int name_type,
1556                     bool bcast, bool recurse,
1557                     const struct sockaddr_storage *to_ss,
1558                     TALLOC_CTX *mem_ctx,
1559                     struct sockaddr_storage **addrs,
1560                     int *num_addrs, uint8_t *flags)
1561 {
1562         TALLOC_CTX *frame = talloc_stackframe();
1563         struct tevent_context *ev;
1564         struct tevent_req *req;
1565         struct timeval timeout;
1566         NTSTATUS status = NT_STATUS_NO_MEMORY;
1567
1568         ev = samba_tevent_context_init(frame);
1569         if (ev == NULL) {
1570                 goto fail;
1571         }
1572         req = name_query_send(ev, ev, name, name_type, bcast, recurse, to_ss);
1573         if (req == NULL) {
1574                 goto fail;
1575         }
1576         if (bcast) {
1577                 timeout = timeval_current_ofs(0, 250000);
1578         } else {
1579                 timeout = timeval_current_ofs(2, 0);
1580         }
1581         if (!tevent_req_set_endtime(req, ev, timeout)) {
1582                 goto fail;
1583         }
1584         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1585                 goto fail;
1586         }
1587         status = name_query_recv(req, mem_ctx, addrs, num_addrs, flags);
1588  fail:
1589         TALLOC_FREE(frame);
1590         return status;
1591 }
1592
1593 /********************************************************
1594  Convert an array if struct sockaddr_storage to struct ip_service
1595  return false on failure.  Port is set to PORT_NONE;
1596  pcount is [in/out] - it is the length of ss_list on input,
1597  and the length of return_iplist on output as we remove any
1598  zero addresses from ss_list.
1599 *********************************************************/
1600
1601 static bool convert_ss2service(struct ip_service **return_iplist,
1602                 const struct sockaddr_storage *ss_list,
1603                 int *pcount)
1604 {
1605         int i;
1606         int orig_count = *pcount;
1607         int real_count = 0;
1608
1609         if (orig_count==0 || !ss_list )
1610                 return False;
1611
1612         /* Filter out zero addrs. */
1613         for ( i=0; i<orig_count; i++ ) {
1614                 if (is_zero_addr(&ss_list[i])) {
1615                         continue;
1616                 }
1617                 real_count++;
1618         }
1619         if (real_count==0) {
1620                 return false;
1621         }
1622
1623         /* copy the ip address; port will be PORT_NONE */
1624         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, real_count)) ==
1625                         NULL) {
1626                 DEBUG(0,("convert_ip2service: malloc failed "
1627                         "for %d enetries!\n", real_count ));
1628                 return False;
1629         }
1630
1631         for ( i=0, real_count = 0; i<orig_count; i++ ) {
1632                 if (is_zero_addr(&ss_list[i])) {
1633                         continue;
1634                 }
1635                 (*return_iplist)[real_count].ss   = ss_list[i];
1636                 (*return_iplist)[real_count].port = PORT_NONE;
1637                 real_count++;
1638         }
1639
1640         *pcount = real_count;
1641         return true;
1642 }
1643
1644 struct name_queries_state {
1645         struct tevent_context *ev;
1646         const char *name;
1647         int name_type;
1648         bool bcast;
1649         bool recurse;
1650         const struct sockaddr_storage *addrs;
1651         int num_addrs;
1652         int wait_msec;
1653         int timeout_msec;
1654
1655         struct tevent_req **subreqs;
1656         int num_received;
1657         int num_sent;
1658
1659         int received_index;
1660         struct sockaddr_storage *result_addrs;
1661         int num_result_addrs;
1662         uint8_t flags;
1663 };
1664
1665 static void name_queries_done(struct tevent_req *subreq);
1666 static void name_queries_next(struct tevent_req *subreq);
1667
1668 /*
1669  * Send a name query to multiple destinations with a wait time in between
1670  */
1671
1672 static struct tevent_req *name_queries_send(
1673         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
1674         const char *name, int name_type,
1675         bool bcast, bool recurse,
1676         const struct sockaddr_storage *addrs,
1677         int num_addrs, int wait_msec, int timeout_msec)
1678 {
1679         struct tevent_req *req, *subreq;
1680         struct name_queries_state *state;
1681
1682         req = tevent_req_create(mem_ctx, &state,
1683                                 struct name_queries_state);
1684         if (req == NULL) {
1685                 return NULL;
1686         }
1687         state->ev = ev;
1688         state->name = name;
1689         state->name_type = name_type;
1690         state->bcast = bcast;
1691         state->recurse = recurse;
1692         state->addrs = addrs;
1693         state->num_addrs = num_addrs;
1694         state->wait_msec = wait_msec;
1695         state->timeout_msec = timeout_msec;
1696
1697         state->subreqs = talloc_zero_array(
1698                 state, struct tevent_req *, num_addrs);
1699         if (tevent_req_nomem(state->subreqs, req)) {
1700                 return tevent_req_post(req, ev);
1701         }
1702         state->num_sent = 0;
1703
1704         subreq = name_query_send(
1705                 state->subreqs, state->ev, name, name_type, bcast, recurse,
1706                 &state->addrs[state->num_sent]);
1707         if (tevent_req_nomem(subreq, req)) {
1708                 return tevent_req_post(req, ev);
1709         }
1710         if (!tevent_req_set_endtime(
1711                     subreq, state->ev,
1712                     timeval_current_ofs(0, state->timeout_msec * 1000))) {
1713                 tevent_req_oom(req);
1714                 return tevent_req_post(req, ev);
1715         }
1716         tevent_req_set_callback(subreq, name_queries_done, req);
1717
1718         state->subreqs[state->num_sent] = subreq;
1719         state->num_sent += 1;
1720
1721         if (state->num_sent < state->num_addrs) {
1722                 subreq = tevent_wakeup_send(
1723                         state, state->ev,
1724                         timeval_current_ofs(0, state->wait_msec * 1000));
1725                 if (tevent_req_nomem(subreq, req)) {
1726                         return tevent_req_post(req, ev);
1727                 }
1728                 tevent_req_set_callback(subreq, name_queries_next, req);
1729         }
1730         return req;
1731 }
1732
1733 static void name_queries_done(struct tevent_req *subreq)
1734 {
1735         struct tevent_req *req = tevent_req_callback_data(
1736                 subreq, struct tevent_req);
1737         struct name_queries_state *state = tevent_req_data(
1738                 req, struct name_queries_state);
1739         int i;
1740         NTSTATUS status;
1741
1742         status = name_query_recv(subreq, state, &state->result_addrs,
1743                                  &state->num_result_addrs, &state->flags);
1744
1745         for (i=0; i<state->num_sent; i++) {
1746                 if (state->subreqs[i] == subreq) {
1747                         break;
1748                 }
1749         }
1750         if (i == state->num_sent) {
1751                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1752                 return;
1753         }
1754         TALLOC_FREE(state->subreqs[i]);
1755
1756         state->num_received += 1;
1757
1758         if (!NT_STATUS_IS_OK(status)) {
1759
1760                 if (state->num_received >= state->num_addrs) {
1761                         tevent_req_nterror(req, status);
1762                         return;
1763                 }
1764                 /*
1765                  * Still outstanding requests, just wait
1766                  */
1767                 return;
1768         }
1769         state->received_index = i;
1770         tevent_req_done(req);
1771 }
1772
1773 static void name_queries_next(struct tevent_req *subreq)
1774 {
1775         struct tevent_req *req = tevent_req_callback_data(
1776                 subreq, struct tevent_req);
1777         struct name_queries_state *state = tevent_req_data(
1778                 req, struct name_queries_state);
1779
1780         if (!tevent_wakeup_recv(subreq)) {
1781                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1782                 return;
1783         }
1784
1785         subreq = name_query_send(
1786                 state->subreqs, state->ev,
1787                 state->name, state->name_type, state->bcast, state->recurse,
1788                 &state->addrs[state->num_sent]);
1789         if (tevent_req_nomem(subreq, req)) {
1790                 return;
1791         }
1792         tevent_req_set_callback(subreq, name_queries_done, req);
1793         if (!tevent_req_set_endtime(
1794                     subreq, state->ev,
1795                     timeval_current_ofs(0, state->timeout_msec * 1000))) {
1796                 tevent_req_oom(req);
1797                 return;
1798         }
1799         state->subreqs[state->num_sent] = subreq;
1800         state->num_sent += 1;
1801
1802         if (state->num_sent < state->num_addrs) {
1803                 subreq = tevent_wakeup_send(
1804                         state, state->ev,
1805                         timeval_current_ofs(0, state->wait_msec * 1000));
1806                 if (tevent_req_nomem(subreq, req)) {
1807                         return;
1808                 }
1809                 tevent_req_set_callback(subreq, name_queries_next, req);
1810         }
1811 }
1812
1813 static NTSTATUS name_queries_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1814                                   struct sockaddr_storage **result_addrs,
1815                                   int *num_result_addrs, uint8_t *flags,
1816                                   int *received_index)
1817 {
1818         struct name_queries_state *state = tevent_req_data(
1819                 req, struct name_queries_state);
1820         NTSTATUS status;
1821
1822         if (tevent_req_is_nterror(req, &status)) {
1823                 return status;
1824         }
1825
1826         if (result_addrs != NULL) {
1827                 *result_addrs = talloc_move(mem_ctx, &state->result_addrs);
1828         }
1829         if (num_result_addrs != NULL) {
1830                 *num_result_addrs = state->num_result_addrs;
1831         }
1832         if (flags != NULL) {
1833                 *flags = state->flags;
1834         }
1835         if (received_index != NULL) {
1836                 *received_index = state->received_index;
1837         }
1838         return NT_STATUS_OK;
1839 }
1840
1841 /********************************************************
1842  Resolve via "bcast" method.
1843 *********************************************************/
1844
1845 struct name_resolve_bcast_state {
1846         struct sockaddr_storage *addrs;
1847         int num_addrs;
1848 };
1849
1850 static void name_resolve_bcast_done(struct tevent_req *subreq);
1851
1852 struct tevent_req *name_resolve_bcast_send(TALLOC_CTX *mem_ctx,
1853                                            struct tevent_context *ev,
1854                                            const char *name,
1855                                            int name_type)
1856 {
1857         struct tevent_req *req, *subreq;
1858         struct name_resolve_bcast_state *state;
1859         struct sockaddr_storage *bcast_addrs;
1860         int i, num_addrs, num_bcast_addrs;
1861
1862         req = tevent_req_create(mem_ctx, &state,
1863                                 struct name_resolve_bcast_state);
1864         if (req == NULL) {
1865                 return NULL;
1866         }
1867
1868         if (lp_disable_netbios()) {
1869                 DEBUG(5, ("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1870                           name, name_type));
1871                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1872                 return tevent_req_post(req, ev);
1873         }
1874
1875         /*
1876          * "bcast" means do a broadcast lookup on all the local interfaces.
1877          */
1878
1879         DEBUG(3, ("name_resolve_bcast: Attempting broadcast lookup "
1880                   "for name %s<0x%x>\n", name, name_type));
1881
1882         num_addrs = iface_count();
1883         bcast_addrs = talloc_array(state, struct sockaddr_storage, num_addrs);
1884         if (tevent_req_nomem(bcast_addrs, req)) {
1885                 return tevent_req_post(req, ev);
1886         }
1887
1888         /*
1889          * Lookup the name on all the interfaces, return on
1890          * the first successful match.
1891          */
1892         num_bcast_addrs = 0;
1893
1894         for (i=0; i<num_addrs; i++) {
1895                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1896
1897                 if (pss->ss_family != AF_INET) {
1898                         continue;
1899                 }
1900                 bcast_addrs[num_bcast_addrs] = *pss;
1901                 num_bcast_addrs += 1;
1902         }
1903
1904         subreq = name_queries_send(state, ev, name, name_type, true, true,
1905                                    bcast_addrs, num_bcast_addrs, 0, 1000);
1906         if (tevent_req_nomem(subreq, req)) {
1907                 return tevent_req_post(req, ev);
1908         }
1909         tevent_req_set_callback(subreq, name_resolve_bcast_done, req);
1910         return req;
1911 }
1912
1913 static void name_resolve_bcast_done(struct tevent_req *subreq)
1914 {
1915         struct tevent_req *req = tevent_req_callback_data(
1916                 subreq, struct tevent_req);
1917         struct name_resolve_bcast_state *state = tevent_req_data(
1918                 req, struct name_resolve_bcast_state);
1919         NTSTATUS status;
1920
1921         status = name_queries_recv(subreq, state,
1922                                    &state->addrs, &state->num_addrs,
1923                                    NULL, NULL);
1924         TALLOC_FREE(subreq);
1925         if (tevent_req_nterror(req, status)) {
1926                 return;
1927         }
1928         tevent_req_done(req);
1929 }
1930
1931 NTSTATUS name_resolve_bcast_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1932                                  struct sockaddr_storage **addrs,
1933                                  int *num_addrs)
1934 {
1935         struct name_resolve_bcast_state *state = tevent_req_data(
1936                 req, struct name_resolve_bcast_state);
1937         NTSTATUS status;
1938
1939         if (tevent_req_is_nterror(req, &status)) {
1940                 return status;
1941         }
1942         *addrs = talloc_move(mem_ctx, &state->addrs);
1943         *num_addrs = state->num_addrs;
1944         return NT_STATUS_OK;
1945 }
1946
1947 NTSTATUS name_resolve_bcast(const char *name,
1948                         int name_type,
1949                         TALLOC_CTX *mem_ctx,
1950                         struct sockaddr_storage **return_iplist,
1951                         int *return_count)
1952 {
1953         TALLOC_CTX *frame = talloc_stackframe();
1954         struct tevent_context *ev;
1955         struct tevent_req *req;
1956         NTSTATUS status = NT_STATUS_NO_MEMORY;
1957
1958         ev = samba_tevent_context_init(frame);
1959         if (ev == NULL) {
1960                 goto fail;
1961         }
1962         req = name_resolve_bcast_send(frame, ev, name, name_type);
1963         if (req == NULL) {
1964                 goto fail;
1965         }
1966         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1967                 goto fail;
1968         }
1969         status = name_resolve_bcast_recv(req, mem_ctx, return_iplist,
1970                                          return_count);
1971  fail:
1972         TALLOC_FREE(frame);
1973         return status;
1974 }
1975
1976 struct query_wins_list_state {
1977         struct tevent_context *ev;
1978         const char *name;
1979         uint8_t name_type;
1980         struct in_addr *servers;
1981         uint32_t num_servers;
1982         struct sockaddr_storage server;
1983         uint32_t num_sent;
1984
1985         struct sockaddr_storage *addrs;
1986         int num_addrs;
1987         uint8_t flags;
1988 };
1989
1990 static void query_wins_list_done(struct tevent_req *subreq);
1991
1992 /*
1993  * Query a list of (replicating) wins servers in sequence, call them
1994  * dead if they don't reply
1995  */
1996
1997 static struct tevent_req *query_wins_list_send(
1998         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
1999         struct in_addr src_ip, const char *name, uint8_t name_type,
2000         struct in_addr *servers, int num_servers)
2001 {
2002         struct tevent_req *req, *subreq;
2003         struct query_wins_list_state *state;
2004
2005         req = tevent_req_create(mem_ctx, &state,
2006                                 struct query_wins_list_state);
2007         if (req == NULL) {
2008                 return NULL;
2009         }
2010         state->ev = ev;
2011         state->name = name;
2012         state->name_type = name_type;
2013         state->servers = servers;
2014         state->num_servers = num_servers;
2015
2016         if (state->num_servers == 0) {
2017                 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2018                 return tevent_req_post(req, ev);
2019         }
2020
2021         in_addr_to_sockaddr_storage(
2022                 &state->server, state->servers[state->num_sent]);
2023
2024         subreq = name_query_send(state, state->ev,
2025                                  state->name, state->name_type,
2026                                  false, true, &state->server);
2027         state->num_sent += 1;
2028         if (tevent_req_nomem(subreq, req)) {
2029                 return tevent_req_post(req, ev);
2030         }
2031         if (!tevent_req_set_endtime(subreq, state->ev,
2032                                     timeval_current_ofs(2, 0))) {
2033                 tevent_req_oom(req);
2034                 return tevent_req_post(req, ev);
2035         }
2036         tevent_req_set_callback(subreq, query_wins_list_done, req);
2037         return req;
2038 }
2039
2040 static void query_wins_list_done(struct tevent_req *subreq)
2041 {
2042         struct tevent_req *req = tevent_req_callback_data(
2043                 subreq, struct tevent_req);
2044         struct query_wins_list_state *state = tevent_req_data(
2045                 req, struct query_wins_list_state);
2046         NTSTATUS status;
2047
2048         status = name_query_recv(subreq, state,
2049                                  &state->addrs, &state->num_addrs,
2050                                  &state->flags);
2051         TALLOC_FREE(subreq);
2052         if (NT_STATUS_IS_OK(status)) {
2053                 tevent_req_done(req);
2054                 return;
2055         }
2056         if (!NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
2057                 tevent_req_nterror(req, status);
2058                 return;
2059         }
2060         wins_srv_died(state->servers[state->num_sent-1],
2061                       my_socket_addr_v4());
2062
2063         if (state->num_sent == state->num_servers) {
2064                 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2065                 return;
2066         }
2067
2068         in_addr_to_sockaddr_storage(
2069                 &state->server, state->servers[state->num_sent]);
2070
2071         subreq = name_query_send(state, state->ev,
2072                                  state->name, state->name_type,
2073                                  false, true, &state->server);
2074         state->num_sent += 1;
2075         if (tevent_req_nomem(subreq, req)) {
2076                 return;
2077         }
2078         if (!tevent_req_set_endtime(subreq, state->ev,
2079                                     timeval_current_ofs(2, 0))) {
2080                 tevent_req_oom(req);
2081                 return;
2082         }
2083         tevent_req_set_callback(subreq, query_wins_list_done, req);
2084 }
2085
2086 static NTSTATUS query_wins_list_recv(struct tevent_req *req,
2087                                      TALLOC_CTX *mem_ctx,
2088                                      struct sockaddr_storage **addrs,
2089                                      int *num_addrs,
2090                                      uint8_t *flags)
2091 {
2092         struct query_wins_list_state *state = tevent_req_data(
2093                 req, struct query_wins_list_state);
2094         NTSTATUS status;
2095
2096         if (tevent_req_is_nterror(req, &status)) {
2097                 return status;
2098         }
2099         if (addrs != NULL) {
2100                 *addrs = talloc_move(mem_ctx, &state->addrs);
2101         }
2102         if (num_addrs != NULL) {
2103                 *num_addrs = state->num_addrs;
2104         }
2105         if (flags != NULL) {
2106                 *flags = state->flags;
2107         }
2108         return NT_STATUS_OK;
2109 }
2110
2111 struct resolve_wins_state {
2112         int num_sent;
2113         int num_received;
2114
2115         struct sockaddr_storage *addrs;
2116         int num_addrs;
2117         uint8_t flags;
2118 };
2119
2120 static void resolve_wins_done(struct tevent_req *subreq);
2121
2122 struct tevent_req *resolve_wins_send(TALLOC_CTX *mem_ctx,
2123                                      struct tevent_context *ev,
2124                                      const char *name,
2125                                      int name_type)
2126 {
2127         struct tevent_req *req, *subreq;
2128         struct resolve_wins_state *state;
2129         char **wins_tags = NULL;
2130         struct sockaddr_storage src_ss;
2131         struct in_addr src_ip;
2132         int i, num_wins_tags;
2133
2134         req = tevent_req_create(mem_ctx, &state,
2135                                 struct resolve_wins_state);
2136         if (req == NULL) {
2137                 return NULL;
2138         }
2139
2140         if (wins_srv_count() < 1) {
2141                 DEBUG(3,("resolve_wins: WINS server resolution selected "
2142                         "and no WINS servers listed.\n"));
2143                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2144                 goto fail;
2145         }
2146
2147         /* the address we will be sending from */
2148         if (!interpret_string_addr(&src_ss, lp_nbt_client_socket_address(),
2149                                 AI_NUMERICHOST|AI_PASSIVE)) {
2150                 zero_sockaddr(&src_ss);
2151         }
2152
2153         if (src_ss.ss_family != AF_INET) {
2154                 char addr[INET6_ADDRSTRLEN];
2155                 print_sockaddr(addr, sizeof(addr), &src_ss);
2156                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
2157                         "on IPv6 address %s\n",
2158                         addr));
2159                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2160                 goto fail;
2161         }
2162
2163         src_ip = ((const struct sockaddr_in *)(void *)&src_ss)->sin_addr;
2164
2165         wins_tags = wins_srv_tags();
2166         if (wins_tags == NULL) {
2167                 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2168                 goto fail;
2169         }
2170
2171         num_wins_tags = 0;
2172         while (wins_tags[num_wins_tags] != NULL) {
2173                 num_wins_tags += 1;
2174         }
2175
2176         for (i=0; i<num_wins_tags; i++) {
2177                 int num_servers, num_alive;
2178                 struct in_addr *servers, *alive;
2179                 int j;
2180
2181                 if (!wins_server_tag_ips(wins_tags[i], talloc_tos(),
2182                                          &servers, &num_servers)) {
2183                         DEBUG(10, ("wins_server_tag_ips failed for tag %s\n",
2184                                    wins_tags[i]));
2185                         continue;
2186                 }
2187
2188                 alive = talloc_array(state, struct in_addr, num_servers);
2189                 if (tevent_req_nomem(alive, req)) {
2190                         goto fail;
2191                 }
2192
2193                 num_alive = 0;
2194                 for (j=0; j<num_servers; j++) {
2195                         struct in_addr wins_ip = servers[j];
2196
2197                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
2198                                 /* yikes! we'll loop forever */
2199                                 continue;
2200                         }
2201                         /* skip any that have been unresponsive lately */
2202                         if (wins_srv_is_dead(wins_ip, src_ip)) {
2203                                 continue;
2204                         }
2205                         DEBUG(3, ("resolve_wins: using WINS server %s "
2206                                  "and tag '%s'\n",
2207                                   inet_ntoa(wins_ip), wins_tags[i]));
2208                         alive[num_alive] = wins_ip;
2209                         num_alive += 1;
2210                 }
2211                 TALLOC_FREE(servers);
2212
2213                 if (num_alive == 0) {
2214                         continue;
2215                 }
2216
2217                 subreq = query_wins_list_send(
2218                         state, ev, src_ip, name, name_type,
2219                         alive, num_alive);
2220                 if (tevent_req_nomem(subreq, req)) {
2221                         goto fail;
2222                 }
2223                 tevent_req_set_callback(subreq, resolve_wins_done, req);
2224                 state->num_sent += 1;
2225         }
2226
2227         if (state->num_sent == 0) {
2228                 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2229                 goto fail;
2230         }
2231
2232         wins_srv_tags_free(wins_tags);
2233         return req;
2234 fail:
2235         wins_srv_tags_free(wins_tags);
2236         return tevent_req_post(req, ev);
2237 }
2238
2239 static void resolve_wins_done(struct tevent_req *subreq)
2240 {
2241         struct tevent_req *req = tevent_req_callback_data(
2242                 subreq, struct tevent_req);
2243         struct resolve_wins_state *state = tevent_req_data(
2244                 req, struct resolve_wins_state);
2245         NTSTATUS status;
2246
2247         status = query_wins_list_recv(subreq, state, &state->addrs,
2248                                       &state->num_addrs, &state->flags);
2249         if (NT_STATUS_IS_OK(status)) {
2250                 tevent_req_done(req);
2251                 return;
2252         }
2253
2254         state->num_received += 1;
2255
2256         if (state->num_received < state->num_sent) {
2257                 /*
2258                  * Wait for the others
2259                  */
2260                 return;
2261         }
2262         tevent_req_nterror(req, status);
2263 }
2264
2265 NTSTATUS resolve_wins_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
2266                            struct sockaddr_storage **addrs,
2267                            int *num_addrs, uint8_t *flags)
2268 {
2269         struct resolve_wins_state *state = tevent_req_data(
2270                 req, struct resolve_wins_state);
2271         NTSTATUS status;
2272
2273         if (tevent_req_is_nterror(req, &status)) {
2274                 return status;
2275         }
2276         if (addrs != NULL) {
2277                 *addrs = talloc_move(mem_ctx, &state->addrs);
2278         }
2279         if (num_addrs != NULL) {
2280                 *num_addrs = state->num_addrs;
2281         }
2282         if (flags != NULL) {
2283                 *flags = state->flags;
2284         }
2285         return NT_STATUS_OK;
2286 }
2287
2288 /********************************************************
2289  Resolve via "wins" method.
2290 *********************************************************/
2291
2292 NTSTATUS resolve_wins(const char *name,
2293                 int name_type,
2294                 TALLOC_CTX *mem_ctx,
2295                 struct sockaddr_storage **return_iplist,
2296                 int *return_count)
2297 {
2298         struct tevent_context *ev;
2299         struct tevent_req *req;
2300         NTSTATUS status = NT_STATUS_NO_MEMORY;
2301
2302         ev = samba_tevent_context_init(talloc_tos());
2303         if (ev == NULL) {
2304                 goto fail;
2305         }
2306         req = resolve_wins_send(ev, ev, name, name_type);
2307         if (req == NULL) {
2308                 goto fail;
2309         }
2310         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
2311                 goto fail;
2312         }
2313         status = resolve_wins_recv(req, mem_ctx, return_iplist, return_count,
2314                                    NULL);
2315 fail:
2316         TALLOC_FREE(ev);
2317         return status;
2318 }
2319
2320 /********************************************************
2321  Resolve via "hosts" method.
2322 *********************************************************/
2323
2324 static NTSTATUS resolve_hosts(const char *name, int name_type,
2325                               TALLOC_CTX *mem_ctx,
2326                               struct sockaddr_storage **return_iplist,
2327                               int *return_count)
2328 {
2329         /*
2330          * "host" means do a localhost, or dns lookup.
2331          */
2332         struct addrinfo hints;
2333         struct addrinfo *ailist = NULL;
2334         struct addrinfo *res = NULL;
2335         int ret = -1;
2336         int i = 0;
2337
2338         if ( name_type != 0x20 && name_type != 0x0) {
2339                 DEBUG(5, ("resolve_hosts: not appropriate "
2340                         "for name type <0x%x>\n",
2341                         name_type));
2342                 return NT_STATUS_INVALID_PARAMETER;
2343         }
2344
2345         *return_iplist = NULL;
2346         *return_count = 0;
2347
2348         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
2349                                 name, name_type));
2350
2351         ZERO_STRUCT(hints);
2352         /* By default make sure it supports TCP. */
2353         hints.ai_socktype = SOCK_STREAM;
2354         hints.ai_flags = AI_ADDRCONFIG;
2355
2356 #if !defined(HAVE_IPV6)
2357         /* Unless we have IPv6, we really only want IPv4 addresses back. */
2358         hints.ai_family = AF_INET;
2359 #endif
2360
2361         ret = getaddrinfo(name,
2362                         NULL,
2363                         &hints,
2364                         &ailist);
2365         if (ret) {
2366                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
2367                         name,
2368                         gai_strerror(ret) ));
2369         }
2370
2371         for (res = ailist; res; res = res->ai_next) {
2372                 struct sockaddr_storage ss;
2373
2374                 if (!res->ai_addr || res->ai_addrlen == 0) {
2375                         continue;
2376                 }
2377
2378                 ZERO_STRUCT(ss);
2379                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
2380
2381                 if (is_zero_addr(&ss)) {
2382                         continue;
2383                 }
2384
2385                 *return_count += 1;
2386
2387                 *return_iplist = talloc_realloc(
2388                         mem_ctx, *return_iplist, struct sockaddr_storage,
2389                         *return_count);
2390                 if (!*return_iplist) {
2391                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
2392                         freeaddrinfo(ailist);
2393                         return NT_STATUS_NO_MEMORY;
2394                 }
2395                 (*return_iplist)[i] = ss;
2396                 i++;
2397         }
2398         if (ailist) {
2399                 freeaddrinfo(ailist);
2400         }
2401         if (*return_count) {
2402                 return NT_STATUS_OK;
2403         }
2404         return NT_STATUS_UNSUCCESSFUL;
2405 }
2406
2407 /********************************************************
2408  Resolve via "ADS" method.
2409 *********************************************************/
2410
2411 /* Special name type used to cause a _kerberos DNS lookup. */
2412 #define KDC_NAME_TYPE 0xDCDC
2413
2414 static NTSTATUS resolve_ads(const char *name,
2415                             int name_type,
2416                             const char *sitename,
2417                             struct ip_service **return_iplist,
2418                             int *return_count)
2419 {
2420         int                     i;
2421         NTSTATUS                status;
2422         TALLOC_CTX              *ctx;
2423         struct dns_rr_srv       *dcs = NULL;
2424         int                     numdcs = 0;
2425         int                     numaddrs = 0;
2426
2427         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
2428             (name_type != 0x1b)) {
2429                 return NT_STATUS_INVALID_PARAMETER;
2430         }
2431
2432         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
2433                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
2434                 return NT_STATUS_NO_MEMORY;
2435         }
2436
2437         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
2438         switch (name_type) {
2439                 case 0x1b:
2440                         DEBUG(5,("resolve_ads: Attempting to resolve "
2441                                  "PDC for %s using DNS\n", name));
2442                         status = ads_dns_query_pdc(ctx,
2443                                                    name,
2444                                                    &dcs,
2445                                                    &numdcs);
2446                         break;
2447
2448                 case 0x1c:
2449                         DEBUG(5,("resolve_ads: Attempting to resolve "
2450                                  "DCs for %s using DNS\n", name));
2451                         status = ads_dns_query_dcs(ctx,
2452                                                    name,
2453                                                    sitename,
2454                                                    &dcs,
2455                                                    &numdcs);
2456                         break;
2457                 case KDC_NAME_TYPE:
2458                         DEBUG(5,("resolve_ads: Attempting to resolve "
2459                                  "KDCs for %s using DNS\n", name));
2460                         status = ads_dns_query_kdcs(ctx,
2461                                                     name,
2462                                                     sitename,
2463                                                     &dcs,
2464                                                     &numdcs);
2465                         break;
2466                 default:
2467                         status = NT_STATUS_INVALID_PARAMETER;
2468                         break;
2469         }
2470
2471         if ( !NT_STATUS_IS_OK( status ) ) {
2472                 talloc_destroy(ctx);
2473                 return status;
2474         }
2475
2476         if (numdcs == 0) {
2477                 *return_iplist = NULL;
2478                 *return_count = 0;
2479                 talloc_destroy(ctx);
2480                 return NT_STATUS_OK;
2481         }
2482
2483         for (i=0;i<numdcs;i++) {
2484                 if (!dcs[i].ss_s) {
2485                         numaddrs += 1;
2486                 } else {
2487                         numaddrs += dcs[i].num_ips;
2488                 }
2489         }
2490
2491         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
2492                         NULL ) {
2493                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
2494                                         numaddrs ));
2495                 talloc_destroy(ctx);
2496                 return NT_STATUS_NO_MEMORY;
2497         }
2498
2499         /* now unroll the list of IP addresses */
2500
2501         *return_count = 0;
2502
2503         for (i = 0; i < numdcs && (*return_count<numaddrs); i++ ) {
2504                 /* If we don't have an IP list for a name, lookup it up */
2505                 if (!dcs[i].ss_s) {
2506                         /* We need to get all IP addresses here. */
2507                         struct addrinfo *res = NULL;
2508                         struct addrinfo *p;
2509                         int extra_addrs = 0;
2510
2511                         if (!interpret_string_addr_internal(&res,
2512                                                 dcs[i].hostname,
2513                                                 0)) {
2514                                 continue;
2515                         }
2516                         /* Add in every IP from the lookup. How
2517                            many is that ? */
2518                         for (p = res; p; p = p->ai_next) {
2519                                 struct sockaddr_storage ss;
2520                                 memcpy(&ss, p->ai_addr, p->ai_addrlen);
2521                                 if (is_zero_addr(&ss)) {
2522                                         continue;
2523                                 }
2524                                 extra_addrs++;
2525                         }
2526                         if (extra_addrs > 1) {
2527                                 /* We need to expand the return_iplist array
2528                                    as we only budgeted for one address. */
2529                                 numaddrs += (extra_addrs-1);
2530                                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
2531                                                 struct ip_service,
2532                                                 numaddrs);
2533                                 if (*return_iplist == NULL) {
2534                                         if (res) {
2535                                                 freeaddrinfo(res);
2536                                         }
2537                                         talloc_destroy(ctx);
2538                                         return NT_STATUS_NO_MEMORY;
2539                                 }
2540                         }
2541                         for (p = res; p; p = p->ai_next) {
2542                                 (*return_iplist)[*return_count].port = dcs[i].port;
2543                                 memcpy(&(*return_iplist)[*return_count].ss,
2544                                                 p->ai_addr,
2545                                                 p->ai_addrlen);
2546                                 if (is_zero_addr(&(*return_iplist)[*return_count].ss)) {
2547                                         continue;
2548                                 }
2549                                 (*return_count)++;
2550                                 /* Should never happen, but still... */
2551                                 if (*return_count>=numaddrs) {
2552                                         break;
2553                                 }
2554                         }
2555                         if (res) {
2556                                 freeaddrinfo(res);
2557                         }
2558                 } else {
2559                         /* use all the IP addresses from the SRV response */
2560                         int j;
2561                         for (j = 0; j < dcs[i].num_ips; j++) {
2562                                 (*return_iplist)[*return_count].port = dcs[i].port;
2563                                 (*return_iplist)[*return_count].ss = dcs[i].ss_s[j];
2564                                 if (is_zero_addr(&(*return_iplist)[*return_count].ss)) {
2565                                         continue;
2566                                 }
2567                                 (*return_count)++;
2568                                 /* Should never happen, but still... */
2569                                 if (*return_count>=numaddrs) {
2570                                         break;
2571                                 }
2572                         }
2573                 }
2574         }
2575
2576         talloc_destroy(ctx);
2577         return NT_STATUS_OK;
2578 }
2579
2580 static const char **filter_out_nbt_lookup(TALLOC_CTX *mem_ctx,
2581                                           const char **resolve_order)
2582 {
2583         size_t i, len, result_idx;
2584         const char **result;
2585
2586         len = 0;
2587         while (resolve_order[len] != NULL) {
2588                 len += 1;
2589         }
2590
2591         result = talloc_array(mem_ctx, const char *, len+1);
2592         if (result == NULL) {
2593                 return NULL;
2594         }
2595
2596         result_idx = 0;
2597
2598         for (i=0; i<len; i++) {
2599                 const char *tok = resolve_order[i];
2600
2601                 if (strequal(tok, "lmhosts") || strequal(tok, "wins") ||
2602                     strequal(tok, "bcast")) {
2603                         continue;
2604                 }
2605                 result[result_idx++] = tok;
2606         }
2607         result[result_idx] = NULL;
2608
2609         return result;
2610 }
2611
2612 /*******************************************************************
2613  Internal interface to resolve a name into an IP address.
2614  Use this function if the string is either an IP address, DNS
2615  or host name or NetBIOS name. This uses the name switch in the
2616  smb.conf to determine the order of name resolution.
2617
2618  Added support for ip addr/port to support ADS ldap servers.
2619  the only place we currently care about the port is in the
2620  resolve_hosts() when looking up DC's via SRV RR entries in DNS
2621 **********************************************************************/
2622
2623 NTSTATUS internal_resolve_name(const char *name,
2624                                 int name_type,
2625                                 const char *sitename,
2626                                 struct ip_service **return_iplist,
2627                                 int *return_count,
2628                                 const char **resolve_order)
2629 {
2630         const char *tok;
2631         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2632         int i;
2633         TALLOC_CTX *frame = NULL;
2634
2635         *return_iplist = NULL;
2636         *return_count = 0;
2637
2638         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
2639                         name, name_type, sitename ? sitename : "(null)"));
2640
2641         if (is_ipaddress(name)) {
2642                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
2643                                 NULL) {
2644                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
2645                         return NT_STATUS_NO_MEMORY;
2646                 }
2647
2648                 /* ignore the port here */
2649                 (*return_iplist)->port = PORT_NONE;
2650
2651                 /* if it's in the form of an IP address then get the lib to interpret it */
2652                 if (!interpret_string_addr(&(*return_iplist)->ss,
2653                                         name, AI_NUMERICHOST)) {
2654                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
2655                                 "failed on %s\n",
2656                                 name));
2657                         SAFE_FREE(*return_iplist);
2658                         return NT_STATUS_INVALID_PARAMETER;
2659                 }
2660                 if (is_zero_addr(&(*return_iplist)->ss)) {
2661                         SAFE_FREE(*return_iplist);
2662                         return NT_STATUS_UNSUCCESSFUL;
2663                 }
2664                 *return_count = 1;
2665                 return NT_STATUS_OK;
2666         }
2667
2668         /* Check name cache */
2669
2670         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
2671                 *return_count = remove_duplicate_addrs2(*return_iplist,
2672                                         *return_count );
2673                 /* This could be a negative response */
2674                 if (*return_count > 0) {
2675                         return NT_STATUS_OK;
2676                 } else {
2677                         return NT_STATUS_UNSUCCESSFUL;
2678                 }
2679         }
2680
2681         /* set the name resolution order */
2682
2683         if (resolve_order && strcmp(resolve_order[0], "NULL") == 0) {
2684                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
2685                 return NT_STATUS_INVALID_PARAMETER;
2686         }
2687
2688         if (!resolve_order || !resolve_order[0]) {
2689                 static const char *host_order[] = { "host", NULL };
2690                 resolve_order = host_order;
2691         }
2692
2693         frame = talloc_stackframe();
2694
2695         if ((strlen(name) > MAX_NETBIOSNAME_LEN - 1) ||
2696             (strchr(name, '.') != NULL)) {
2697                 /*
2698                  * Don't do NBT lookup, the name would not fit anyway
2699                  */
2700                 resolve_order = filter_out_nbt_lookup(frame, resolve_order);
2701                 if (resolve_order == NULL) {
2702                         TALLOC_FREE(frame);
2703                         return NT_STATUS_NO_MEMORY;
2704                 }
2705         }
2706
2707         /* iterate through the name resolution backends */
2708
2709         for (i=0; resolve_order[i]; i++) {
2710                 tok = resolve_order[i];
2711
2712                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
2713                         struct sockaddr_storage *ss_list;
2714                         status = resolve_hosts(name, name_type,
2715                                                talloc_tos(), &ss_list,
2716                                                return_count);
2717                         if (NT_STATUS_IS_OK(status)) {
2718                                 if (!convert_ss2service(return_iplist,
2719                                                         ss_list,
2720                                                         return_count)) {
2721                                         status = NT_STATUS_NO_MEMORY;
2722                                 }
2723                                 goto done;
2724                         }
2725                 } else if(strequal( tok, "kdc")) {
2726                         /* deal with KDC_NAME_TYPE names here.
2727                          * This will result in a SRV record lookup */
2728                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
2729                                              return_iplist, return_count);
2730                         if (NT_STATUS_IS_OK(status)) {
2731                                 /* Ensure we don't namecache
2732                                  * this with the KDC port. */
2733                                 name_type = KDC_NAME_TYPE;
2734                                 goto done;
2735                         }
2736                 } else if(strequal( tok, "ads")) {
2737                         /* deal with 0x1c and 0x1b names here.
2738                          * This will result in a SRV record lookup */
2739                         status = resolve_ads(name, name_type, sitename,
2740                                              return_iplist, return_count);
2741                         if (NT_STATUS_IS_OK(status)) {
2742                                 goto done;
2743                         }
2744                 } else if (strequal(tok, "lmhosts")) {
2745                         struct sockaddr_storage *ss_list;
2746                         status = resolve_lmhosts_file_as_sockaddr(
2747                                 get_dyn_LMHOSTSFILE(), name, name_type,
2748                                 talloc_tos(), &ss_list, return_count);
2749                         if (NT_STATUS_IS_OK(status)) {
2750                                 if (!convert_ss2service(return_iplist,
2751                                                         ss_list,
2752                                                         return_count)) {
2753                                         status = NT_STATUS_NO_MEMORY;
2754                                 }
2755                                 goto done;
2756                         }
2757                 } else if (strequal(tok, "wins")) {
2758                         /* don't resolve 1D via WINS */
2759                         struct sockaddr_storage *ss_list;
2760                         if (name_type != 0x1D) {
2761                                 status = resolve_wins(name, name_type,
2762                                                       talloc_tos(),
2763                                                       &ss_list,
2764                                                       return_count);
2765                                 if (NT_STATUS_IS_OK(status)) {
2766                                         if (!convert_ss2service(return_iplist,
2767                                                                 ss_list,
2768                                                                 return_count)) {
2769                                                 status = NT_STATUS_NO_MEMORY;
2770                                         }
2771                                         goto done;
2772                                 }
2773                         }
2774                 } else if (strequal(tok, "bcast")) {
2775                         struct sockaddr_storage *ss_list;
2776                         status = name_resolve_bcast(
2777                                 name, name_type, talloc_tos(),
2778                                 &ss_list, return_count);
2779                         if (NT_STATUS_IS_OK(status)) {
2780                                 if (!convert_ss2service(return_iplist,
2781                                                         ss_list,
2782                                                         return_count)) {
2783                                         status = NT_STATUS_NO_MEMORY;
2784                                 }
2785                                 goto done;
2786                         }
2787                 } else {
2788                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
2789                                 tok));
2790                 }
2791         }
2792
2793         /* All of the resolve_* functions above have returned false. */
2794
2795         TALLOC_FREE(frame);
2796         SAFE_FREE(*return_iplist);
2797         *return_count = 0;
2798
2799         return NT_STATUS_UNSUCCESSFUL;
2800
2801   done:
2802
2803         /* Remove duplicate entries.  Some queries, notably #1c (domain
2804         controllers) return the PDC in iplist[0] and then all domain
2805         controllers including the PDC in iplist[1..n].  Iterating over
2806         the iplist when the PDC is down will cause two sets of timeouts. */
2807
2808         *return_count = remove_duplicate_addrs2(*return_iplist, *return_count );
2809
2810         /* Save in name cache */
2811         if ( DEBUGLEVEL >= 100 ) {
2812                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
2813                         char addr[INET6_ADDRSTRLEN];
2814                         print_sockaddr(addr, sizeof(addr),
2815                                         &(*return_iplist)[i].ss);
2816                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
2817                                         name,
2818                                         name_type,
2819                                         addr,
2820                                         (*return_iplist)[i].port));
2821                 }
2822         }
2823
2824         if (*return_count) {
2825                 namecache_store(name, name_type, *return_count, *return_iplist);
2826         }
2827
2828         /* Display some debugging info */
2829
2830         if ( DEBUGLEVEL >= 10 ) {
2831                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
2832                                         *return_count));
2833
2834                 for (i = 0; i < *return_count; i++) {
2835                         char addr[INET6_ADDRSTRLEN];
2836                         print_sockaddr(addr, sizeof(addr),
2837                                         &(*return_iplist)[i].ss);
2838                         DEBUGADD(10, ("%s:%d ",
2839                                         addr,
2840                                         (*return_iplist)[i].port));
2841                 }
2842                 DEBUG(10, ("\n"));
2843         }
2844
2845         TALLOC_FREE(frame);
2846         return status;
2847 }
2848
2849 /********************************************************
2850  Internal interface to resolve a name into one IP address.
2851  Use this function if the string is either an IP address, DNS
2852  or host name or NetBIOS name. This uses the name switch in the
2853  smb.conf to determine the order of name resolution.
2854 *********************************************************/
2855
2856 bool resolve_name(const char *name,
2857                 struct sockaddr_storage *return_ss,
2858                 int name_type,
2859                 bool prefer_ipv4)
2860 {
2861         struct ip_service *ss_list = NULL;
2862         char *sitename = NULL;
2863         int count = 0;
2864         NTSTATUS status;
2865
2866         if (is_ipaddress(name)) {
2867                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2868         }
2869
2870         sitename = sitename_fetch(talloc_tos(), lp_realm()); /* wild guess */
2871
2872         status = internal_resolve_name(name, name_type, sitename,
2873                                        &ss_list, &count,
2874                                        lp_name_resolve_order());
2875         if (NT_STATUS_IS_OK(status)) {
2876                 int i;
2877
2878                 if (prefer_ipv4) {
2879                         for (i=0; i<count; i++) {
2880                                 if (!is_zero_addr(&ss_list[i].ss) &&
2881                                     !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss) &&
2882                                                 (ss_list[i].ss.ss_family == AF_INET)) {
2883                                         *return_ss = ss_list[i].ss;
2884                                         SAFE_FREE(ss_list);
2885                                         TALLOC_FREE(sitename);
2886                                         return True;
2887                                 }
2888                         }
2889                 }
2890
2891                 /* only return valid addresses for TCP connections */
2892                 for (i=0; i<count; i++) {
2893                         if (!is_zero_addr(&ss_list[i].ss) &&
2894                             !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss)) {
2895                                 *return_ss = ss_list[i].ss;
2896                                 SAFE_FREE(ss_list);
2897                                 TALLOC_FREE(sitename);
2898                                 return True;
2899                         }
2900                 }
2901         }
2902
2903         SAFE_FREE(ss_list);
2904         TALLOC_FREE(sitename);
2905         return False;
2906 }
2907
2908 /********************************************************
2909  Internal interface to resolve a name into a list of IP addresses.
2910  Use this function if the string is either an IP address, DNS
2911  or host name or NetBIOS name. This uses the name switch in the
2912  smb.conf to determine the order of name resolution.
2913 *********************************************************/
2914
2915 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2916                 const char *name,
2917                 int name_type,
2918                 struct sockaddr_storage **return_ss_arr,
2919                 unsigned int *p_num_entries)
2920 {
2921         struct ip_service *ss_list = NULL;
2922         char *sitename = NULL;
2923         int count = 0;
2924         int i;
2925         unsigned int num_entries;
2926         NTSTATUS status;
2927
2928         *p_num_entries = 0;
2929         *return_ss_arr = NULL;
2930
2931         if (is_ipaddress(name)) {
2932                 *return_ss_arr = talloc(ctx, struct sockaddr_storage);
2933                 if (!*return_ss_arr) {
2934                         return NT_STATUS_NO_MEMORY;
2935                 }
2936                 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2937                         TALLOC_FREE(*return_ss_arr);
2938                         return NT_STATUS_BAD_NETWORK_NAME;
2939                 }
2940                 *p_num_entries = 1;
2941                 return NT_STATUS_OK;
2942         }
2943
2944         sitename = sitename_fetch(ctx, lp_realm()); /* wild guess */
2945
2946         status = internal_resolve_name(name, name_type, sitename,
2947                                                   &ss_list, &count,
2948                                                   lp_name_resolve_order());
2949         TALLOC_FREE(sitename);
2950
2951         if (!NT_STATUS_IS_OK(status)) {
2952                 return status;
2953         }
2954
2955         /* only return valid addresses for TCP connections */
2956         for (i=0, num_entries = 0; i<count; i++) {
2957                 if (!is_zero_addr(&ss_list[i].ss) &&
2958                     !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss)) {
2959                         num_entries++;
2960                 }
2961         }
2962         if (num_entries == 0) {
2963                 SAFE_FREE(ss_list);
2964                 return NT_STATUS_BAD_NETWORK_NAME;
2965         }
2966
2967         *return_ss_arr = talloc_array(ctx,
2968                                 struct sockaddr_storage,
2969                                 num_entries);
2970         if (!(*return_ss_arr)) {
2971                 SAFE_FREE(ss_list);
2972                 return NT_STATUS_NO_MEMORY;
2973         }
2974
2975         for (i=0, num_entries = 0; i<count; i++) {
2976                 if (!is_zero_addr(&ss_list[i].ss) &&
2977                     !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss)) {
2978                         (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2979                 }
2980         }
2981
2982         status = NT_STATUS_OK;
2983         *p_num_entries = num_entries;
2984
2985         SAFE_FREE(ss_list);
2986         return NT_STATUS_OK;
2987 }
2988
2989 /********************************************************
2990  Find the IP address of the master browser or DMB for a workgroup.
2991 *********************************************************/
2992
2993 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2994 {
2995         struct ip_service *ip_list = NULL;
2996         int count = 0;
2997         NTSTATUS status;
2998
2999         if (lp_disable_netbios()) {
3000                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
3001                 return false;
3002         }
3003
3004         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
3005                                        lp_name_resolve_order());
3006         if (NT_STATUS_IS_OK(status)) {
3007                 *master_ss = ip_list[0].ss;
3008                 SAFE_FREE(ip_list);
3009                 return true;
3010         }
3011
3012         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
3013                                        lp_name_resolve_order());
3014         if (NT_STATUS_IS_OK(status)) {
3015                 *master_ss = ip_list[0].ss;
3016                 SAFE_FREE(ip_list);
3017                 return true;
3018         }
3019
3020         SAFE_FREE(ip_list);
3021         return false;
3022 }
3023
3024 /********************************************************
3025  Get the IP address list of the primary domain controller
3026  for a domain.
3027 *********************************************************/
3028
3029 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
3030 {
3031         struct ip_service *ip_list = NULL;
3032         int count = 0;
3033         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
3034         static const char *ads_order[] = { "ads", NULL };
3035         /* Look up #1B name */
3036
3037         if (lp_security() == SEC_ADS) {
3038                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
3039                                                &count, ads_order);
3040         }
3041
3042         if (!NT_STATUS_IS_OK(status) || count == 0) {
3043                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
3044                                                &count,
3045                                                lp_name_resolve_order());
3046                 if (!NT_STATUS_IS_OK(status)) {
3047                         SAFE_FREE(ip_list);
3048                         return false;
3049                 }
3050         }
3051
3052         /* if we get more than 1 IP back we have to assume it is a
3053            multi-homed PDC and not a mess up */
3054
3055         if ( count > 1 ) {
3056                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
3057                 sort_service_list(ip_list, count);
3058         }
3059
3060         *pss = ip_list[0].ss;
3061         SAFE_FREE(ip_list);
3062         return true;
3063 }
3064
3065 /* Private enum type for lookups. */
3066
3067 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
3068
3069 /********************************************************
3070  Get the IP address list of the domain controllers for
3071  a domain.
3072 *********************************************************/
3073
3074 static NTSTATUS get_dc_list(const char *domain,
3075                         const char *sitename,
3076                         struct ip_service **ip_list,
3077                         int *count,
3078                         enum dc_lookup_type lookup_type,
3079                         bool *ordered)
3080 {
3081         const char **resolve_order = NULL;
3082         char *saf_servername = NULL;
3083         char *pserver = NULL;
3084         const char *p;
3085         char *port_str = NULL;
3086         int port;
3087         char *name;
3088         int num_addresses = 0;
3089         int  local_count, i, j;
3090         struct ip_service *return_iplist = NULL;
3091         struct ip_service *auto_ip_list = NULL;
3092         bool done_auto_lookup = false;
3093         int auto_count = 0;
3094         NTSTATUS status;
3095         TALLOC_CTX *ctx = talloc_init("get_dc_list");
3096         int auto_name_type = 0x1C;
3097
3098         *ip_list = NULL;
3099         *count = 0;
3100
3101         if (!ctx) {
3102                 return NT_STATUS_NO_MEMORY;
3103         }
3104
3105         *ordered = False;
3106
3107         /* if we are restricted to solely using DNS for looking
3108            up a domain controller, make sure that host lookups
3109            are enabled for the 'name resolve order'.  If host lookups
3110            are disabled and ads_only is True, then set the string to
3111            NULL. */
3112
3113         resolve_order = lp_name_resolve_order();
3114         if (!resolve_order) {
3115                 status = NT_STATUS_NO_MEMORY;
3116                 goto out;
3117         }
3118         if (lookup_type == DC_ADS_ONLY)  {
3119                 if (str_list_check_ci(resolve_order, "host")) {
3120                         static const char *ads_order[] = { "ads", NULL };
3121                         resolve_order = ads_order;
3122
3123                         /* DNS SRV lookups used by the ads resolver
3124                            are already sorted by priority and weight */
3125                         *ordered = true;
3126                 } else {
3127                         /* this is quite bizarre! */
3128                         static const char *null_order[] = { "NULL", NULL };
3129                         resolve_order = null_order;
3130                 }
3131         } else if (lookup_type == DC_KDC_ONLY) {
3132                 static const char *kdc_order[] = { "kdc", NULL };
3133                 /* DNS SRV lookups used by the ads/kdc resolver
3134                    are already sorted by priority and weight */
3135                 *ordered = true;
3136                 resolve_order = kdc_order;
3137                 auto_name_type = KDC_NAME_TYPE;
3138         }
3139
3140         /* fetch the server we have affinity for.  Add the
3141            'password server' list to a search for our domain controllers */
3142
3143         saf_servername = saf_fetch(ctx, domain);
3144
3145         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
3146                 pserver = talloc_asprintf(ctx, "%s, %s",
3147                         saf_servername ? saf_servername : "",
3148                         lp_password_server());
3149         } else {
3150                 pserver = talloc_asprintf(ctx, "%s, *",
3151                         saf_servername ? saf_servername : "");
3152         }
3153
3154         TALLOC_FREE(saf_servername);
3155         if (!pserver) {
3156                 status = NT_STATUS_NO_MEMORY;
3157                 goto out;
3158         }
3159
3160         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
3161
3162         /*
3163          * if '*' appears in the "password server" list then add
3164          * an auto lookup to the list of manually configured
3165          * DC's.  If any DC is listed by name, then the list should be
3166          * considered to be ordered
3167          */
3168
3169         p = pserver;
3170         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
3171                 if (!done_auto_lookup && strequal(name, "*")) {
3172                         status = internal_resolve_name(domain, auto_name_type,
3173                                                        sitename,
3174                                                        &auto_ip_list,
3175                                                        &auto_count,
3176                                                        resolve_order);
3177                         if (NT_STATUS_IS_OK(status)) {
3178                                 num_addresses += auto_count;
3179                         }
3180                         done_auto_lookup = true;
3181                         DEBUG(8,("Adding %d DC's from auto lookup\n",
3182                                                 auto_count));
3183                 } else  {
3184                         num_addresses++;
3185                 }
3186         }
3187
3188         /* if we have no addresses and haven't done the auto lookup, then
3189            just return the list of DC's.  Or maybe we just failed. */
3190
3191         if (num_addresses == 0) {
3192                 if (done_auto_lookup) {
3193                         DEBUG(4,("get_dc_list: no servers found\n"));
3194                         status = NT_STATUS_NO_LOGON_SERVERS;
3195                         goto out;
3196                 }
3197                 status = internal_resolve_name(domain, auto_name_type,
3198                                                sitename, ip_list,
3199                                              count, resolve_order);
3200                 goto out;
3201         }
3202
3203         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
3204                                         num_addresses)) == NULL) {
3205                 DEBUG(3,("get_dc_list: malloc fail !\n"));
3206                 status = NT_STATUS_NO_MEMORY;
3207                 goto out;
3208         }
3209
3210         p = pserver;
3211         local_count = 0;
3212
3213         /* fill in the return list now with real IP's */
3214
3215         while ((local_count<num_addresses) &&
3216                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
3217                 struct sockaddr_storage name_ss;
3218
3219                 /* copy any addresses from the auto lookup */
3220
3221                 if (strequal(name, "*")) {
3222                         for (j=0; j<auto_count; j++) {
3223                                 char addr[INET6_ADDRSTRLEN];
3224                                 print_sockaddr(addr,
3225                                                 sizeof(addr),
3226                                                 &auto_ip_list[j].ss);
3227                                 /* Check for and don't copy any
3228                                  * known bad DC IP's. */
3229                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
3230                                                 domain,
3231                                                 addr))) {
3232                                         DEBUG(5,("get_dc_list: "
3233                                                 "negative entry %s removed "
3234                                                 "from DC list\n",
3235                                                 addr));
3236                                         continue;
3237                                 }
3238                                 return_iplist[local_count].ss =
3239                                         auto_ip_list[j].ss;
3240                                 return_iplist[local_count].port =
3241                                         auto_ip_list[j].port;
3242                                 local_count++;
3243                         }
3244                         continue;
3245                 }
3246
3247                 /* added support for address:port syntax for ads
3248                  * (not that I think anyone will ever run the LDAP
3249                  * server in an AD domain on something other than
3250                  * port 389
3251                  * However, the port should not be used for kerberos
3252                  */
3253
3254                 port = (lookup_type == DC_ADS_ONLY) ? LDAP_PORT :
3255                         ((lookup_type == DC_KDC_ONLY) ? DEFAULT_KRB5_PORT :
3256                          PORT_NONE);
3257                 if ((port_str=strchr(name, ':')) != NULL) {
3258                         *port_str = '\0';
3259                         if (lookup_type != DC_KDC_ONLY) {
3260                                 port_str++;
3261                                 port = atoi(port_str);
3262                         }
3263                 }
3264
3265                 /* explicit lookup; resolve_name() will
3266                  * handle names & IP addresses */
3267                 if (resolve_name( name, &name_ss, 0x20, true )) {
3268                         char addr[INET6_ADDRSTRLEN];
3269                         print_sockaddr(addr,
3270                                         sizeof(addr),
3271                                         &name_ss);
3272
3273                         /* Check for and don't copy any known bad DC IP's. */
3274                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
3275                                                         addr)) ) {
3276                                 DEBUG(5,("get_dc_list: negative entry %s "
3277                                         "removed from DC list\n",
3278                                         name ));
3279                                 continue;
3280                         }
3281
3282                         return_iplist[local_count].ss = name_ss;
3283                         return_iplist[local_count].port = port;
3284                         local_count++;
3285                         *ordered = true;
3286                 }
3287         }
3288
3289         /* need to remove duplicates in the list if we have any
3290            explicit password servers */
3291
3292         local_count = remove_duplicate_addrs2(return_iplist, local_count );
3293
3294         /* For DC's we always prioritize IPv4 due to W2K3 not
3295          * supporting LDAP, KRB5 or CLDAP over IPv6. */
3296
3297         if (local_count && return_iplist) {
3298                 prioritize_ipv4_list(return_iplist, local_count);
3299         }
3300
3301         if ( DEBUGLEVEL >= 4 ) {
3302                 DEBUG(4,("get_dc_list: returning %d ip addresses "
3303                                 "in an %sordered list\n",
3304                                 local_count,
3305                                 *ordered ? "":"un"));
3306                 DEBUG(4,("get_dc_list: "));
3307                 for ( i=0; i<local_count; i++ ) {
3308                         char addr[INET6_ADDRSTRLEN];
3309                         print_sockaddr(addr,
3310                                         sizeof(addr),
3311                                         &return_iplist[i].ss);
3312                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
3313                 }
3314                 DEBUGADD(4,("\n"));
3315         }
3316
3317         *ip_list = return_iplist;
3318         *count = local_count;
3319
3320         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
3321
3322   out:
3323
3324         if (!NT_STATUS_IS_OK(status)) {
3325                 SAFE_FREE(return_iplist);
3326                 *ip_list = NULL;
3327                 *count = 0;
3328         }
3329
3330         SAFE_FREE(auto_ip_list);
3331         TALLOC_FREE(ctx);
3332         return status;
3333 }
3334
3335 /*********************************************************************
3336  Small wrapper function to get the DC list and sort it if neccessary.
3337 *********************************************************************/
3338
3339 NTSTATUS get_sorted_dc_list( const char *domain,
3340                         const char *sitename,
3341                         struct ip_service **ip_list,
3342                         int *count,
3343                         bool ads_only )
3344 {
3345         bool ordered = false;
3346         NTSTATUS status;
3347         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
3348
3349         *ip_list = NULL;
3350         *count = 0;
3351
3352         DEBUG(8,("get_sorted_dc_list: attempting lookup "
3353                 "for name %s (sitename %s)\n",
3354                 domain,
3355                  sitename ? sitename : "NULL"));
3356
3357         if (ads_only) {
3358                 lookup_type = DC_ADS_ONLY;
3359         }
3360
3361         status = get_dc_list(domain, sitename, ip_list,
3362                         count, lookup_type, &ordered);
3363         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
3364             && sitename) {
3365                 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
3366                          " in site %s, fallback to all servers\n",
3367                          domain, sitename));
3368                 status = get_dc_list(domain, NULL, ip_list,
3369                                      count, lookup_type, &ordered);
3370         }
3371
3372         if (!NT_STATUS_IS_OK(status)) {
3373                 SAFE_FREE(*ip_list);
3374                 *count = 0;
3375                 return status;
3376         }
3377
3378         /* only sort if we don't already have an ordered list */
3379         if (!ordered) {
3380                 sort_service_list(*ip_list, *count);
3381         }
3382
3383         return NT_STATUS_OK;
3384 }
3385
3386 /*********************************************************************
3387  Get the KDC list - re-use all the logic in get_dc_list.
3388 *********************************************************************/
3389
3390 NTSTATUS get_kdc_list( const char *realm,
3391                         const char *sitename,
3392                         struct ip_service **ip_list,
3393                         int *count)
3394 {
3395         bool ordered;
3396         NTSTATUS status;
3397
3398         *count = 0;
3399         *ip_list = NULL;
3400
3401         status = get_dc_list(realm, sitename, ip_list,
3402                         count, DC_KDC_ONLY, &ordered);
3403
3404         if (!NT_STATUS_IS_OK(status)) {
3405                 SAFE_FREE(*ip_list);
3406                 *count = 0;
3407                 return status;
3408         }
3409
3410         /* only sort if we don't already have an ordered list */
3411         if ( !ordered ) {
3412                 sort_service_list(*ip_list, *count);
3413         }
3414
3415         return NT_STATUS_OK;
3416 }