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