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