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