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