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