s3: Make node_status_query use /tmp/.nmbd/unexpected
[kai/samba-autobuild/.git] / source3 / libsmb / namequery.c
1 /*
2    Unix SMB/CIFS implementation.
3    name query routines
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Jeremy Allison 2007.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "libads/sitename_cache.h"
23 #include "libads/dns.h"
24 #include "../libcli/netlogon.h"
25 #include "librpc/gen_ndr/messaging.h"
26 #include "lib/async_req/async_sock.h"
27
28 /* nmbd.c sets this to True. */
29 bool global_in_nmbd = False;
30
31 /****************************
32  * SERVER AFFINITY ROUTINES *
33  ****************************/
34
35  /* Server affinity is the concept of preferring the last domain
36     controller with whom you had a successful conversation */
37
38 /****************************************************************************
39 ****************************************************************************/
40 #define SAFKEY_FMT      "SAF/DOMAIN/%s"
41 #define SAF_TTL         900
42 #define SAFJOINKEY_FMT  "SAFJOIN/DOMAIN/%s"
43 #define SAFJOIN_TTL     3600
44
45 static char *saf_key(const char *domain)
46 {
47         char *keystr;
48
49         asprintf_strupper_m(&keystr, SAFKEY_FMT, domain);
50
51         return keystr;
52 }
53
54 static char *saf_join_key(const char *domain)
55 {
56         char *keystr;
57
58         asprintf_strupper_m(&keystr, SAFJOINKEY_FMT, domain);
59
60         return keystr;
61 }
62
63 /****************************************************************************
64 ****************************************************************************/
65
66 bool saf_store( const char *domain, const char *servername )
67 {
68         char *key;
69         time_t expire;
70         bool ret = False;
71
72         if ( !domain || !servername ) {
73                 DEBUG(2,("saf_store: "
74                         "Refusing to store empty domain or servername!\n"));
75                 return False;
76         }
77
78         if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
79                 DEBUG(0,("saf_store: "
80                         "refusing to store 0 length domain or servername!\n"));
81                 return False;
82         }
83
84         key = saf_key( domain );
85         expire = time( NULL ) + lp_parm_int(-1, "saf","ttl", SAF_TTL);
86
87         DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
88                 domain, servername, (unsigned int)expire ));
89
90         ret = gencache_set( key, servername, expire );
91
92         SAFE_FREE( key );
93
94         return ret;
95 }
96
97 bool saf_join_store( const char *domain, const char *servername )
98 {
99         char *key;
100         time_t expire;
101         bool ret = False;
102
103         if ( !domain || !servername ) {
104                 DEBUG(2,("saf_join_store: Refusing to store empty domain or servername!\n"));
105                 return False;
106         }
107
108         if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
109                 DEBUG(0,("saf_join_store: refusing to store 0 length domain or servername!\n"));
110                 return False;
111         }
112
113         key = saf_join_key( domain );
114         expire = time( NULL ) + lp_parm_int(-1, "saf","join ttl", SAFJOIN_TTL);
115
116         DEBUG(10,("saf_join_store: domain = [%s], server = [%s], expire = [%u]\n",
117                 domain, servername, (unsigned int)expire ));
118
119         ret = gencache_set( key, servername, expire );
120
121         SAFE_FREE( key );
122
123         return ret;
124 }
125
126 bool saf_delete( const char *domain )
127 {
128         char *key;
129         bool ret = False;
130
131         if ( !domain ) {
132                 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
133                 return False;
134         }
135
136         key = saf_join_key(domain);
137         ret = gencache_del(key);
138         SAFE_FREE(key);
139
140         if (ret) {
141                 DEBUG(10,("saf_delete[join]: domain = [%s]\n", domain ));
142         }
143
144         key = saf_key(domain);
145         ret = gencache_del(key);
146         SAFE_FREE(key);
147
148         if (ret) {
149                 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
150         }
151
152         return ret;
153 }
154
155 /****************************************************************************
156 ****************************************************************************/
157
158 char *saf_fetch( const char *domain )
159 {
160         char *server = NULL;
161         time_t timeout;
162         bool ret = False;
163         char *key = NULL;
164
165         if ( !domain || strlen(domain) == 0) {
166                 DEBUG(2,("saf_fetch: Empty domain name!\n"));
167                 return NULL;
168         }
169
170         key = saf_join_key( domain );
171
172         ret = gencache_get( key, &server, &timeout );
173
174         SAFE_FREE( key );
175
176         if ( ret ) {
177                 DEBUG(5,("saf_fetch[join]: Returning \"%s\" for \"%s\" domain\n",
178                         server, domain ));
179                 return server;
180         }
181
182         key = saf_key( domain );
183
184         ret = gencache_get( key, &server, &timeout );
185
186         SAFE_FREE( key );
187
188         if ( !ret ) {
189                 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n",
190                                         domain ));
191         } else {
192                 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
193                         server, domain ));
194         }
195
196         return server;
197 }
198
199 /****************************************************************************
200  Generate a random trn_id.
201 ****************************************************************************/
202
203 static int generate_trn_id(void)
204 {
205         uint16 id;
206
207         generate_random_buffer((uint8 *)&id, sizeof(id));
208
209         return id % (unsigned)0x7FFF;
210 }
211
212 /****************************************************************************
213  Parse a node status response into an array of structures.
214 ****************************************************************************/
215
216 static struct node_status *parse_node_status(TALLOC_CTX *mem_ctx, char *p,
217                                 int *num_names,
218                                 struct node_status_extra *extra)
219 {
220         struct node_status *ret;
221         int i;
222
223         *num_names = CVAL(p,0);
224
225         if (*num_names == 0)
226                 return NULL;
227
228         ret = TALLOC_ARRAY(mem_ctx, struct node_status,*num_names);
229         if (!ret)
230                 return NULL;
231
232         p++;
233         for (i=0;i< *num_names;i++) {
234                 StrnCpy(ret[i].name,p,15);
235                 trim_char(ret[i].name,'\0',' ');
236                 ret[i].type = CVAL(p,15);
237                 ret[i].flags = p[16];
238                 p += 18;
239                 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
240                            ret[i].type, ret[i].flags));
241         }
242         /*
243          * Also, pick up the MAC address ...
244          */
245         if (extra) {
246                 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
247         }
248         return ret;
249 }
250
251 struct sock_packet_read_state {
252         struct tevent_context *ev;
253         enum packet_type type;
254         int trn_id;
255
256         struct nb_packet_reader *reader;
257         struct tevent_req *reader_req;
258
259         int sock;
260         struct tevent_req *socket_req;
261         uint8_t buf[1024];
262         struct sockaddr_storage addr;
263         socklen_t addr_len;
264
265         bool (*validator)(struct packet_struct *p,
266                           void *private_data);
267         void *private_data;
268
269         struct packet_struct *packet;
270 };
271
272 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s);
273 static void sock_packet_read_got_packet(struct tevent_req *subreq);
274 static void sock_packet_read_got_socket(struct tevent_req *subreq);
275
276 static struct tevent_req *sock_packet_read_send(
277         TALLOC_CTX *mem_ctx,
278         struct tevent_context *ev,
279         int sock, /* dgram socket */
280         struct nb_packet_reader *reader,
281         enum packet_type type,
282         int trn_id,
283         bool (*validator)(struct packet_struct *p, void *private_data),
284         void *private_data)
285 {
286         struct tevent_req *req;
287         struct sock_packet_read_state *state;
288
289         req = tevent_req_create(mem_ctx, &state,
290                                 struct sock_packet_read_state);
291         if (req == NULL) {
292                 return NULL;
293         }
294         talloc_set_destructor(state, sock_packet_read_state_destructor);
295         state->ev = ev;
296         state->reader = reader;
297         state->sock = sock;
298         state->type = type;
299         state->trn_id = trn_id;
300         state->validator = validator;
301         state->private_data = private_data;
302
303         if (reader != NULL) {
304                 state->reader_req = nb_packet_read_send(state, ev, reader);
305                 if (tevent_req_nomem(state->reader_req, req)) {
306                         return tevent_req_post(req, ev);
307                 }
308                 tevent_req_set_callback(
309                         state->reader_req, sock_packet_read_got_packet, req);
310         }
311
312         state->addr_len = sizeof(state->addr);
313         state->socket_req = recvfrom_send(state, ev, sock,
314                                           state->buf, sizeof(state->buf), 0,
315                                           &state->addr, &state->addr_len);
316         if (tevent_req_nomem(state->socket_req, req)) {
317                 return tevent_req_post(req, ev);
318         }
319         tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
320                                 req);
321
322         return req;
323 }
324
325 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s)
326 {
327         if (s->packet != NULL) {
328                 free_packet(s->packet);
329                 s->packet = NULL;
330         }
331         return 0;
332 }
333
334 static void sock_packet_read_got_packet(struct tevent_req *subreq)
335 {
336         struct tevent_req *req = tevent_req_callback_data(
337                 subreq, struct tevent_req);
338         struct sock_packet_read_state *state = tevent_req_data(
339                 req, struct sock_packet_read_state);
340         NTSTATUS status;
341
342         status = nb_packet_read_recv(subreq, &state->packet);
343
344         TALLOC_FREE(state->reader_req);
345
346         if (!NT_STATUS_IS_OK(status)) {
347                 if (state->socket_req != NULL) {
348                         /*
349                          * Still waiting for socket
350                          */
351                         return;
352                 }
353                 /*
354                  * Both socket and packet reader failed
355                  */
356                 tevent_req_nterror(req, status);
357                 return;
358         }
359
360         if ((state->validator != NULL) &&
361             !state->validator(state->packet, state->private_data)) {
362                 DEBUG(10, ("validator failed\n"));
363
364                 free_packet(state->packet);
365                 state->packet = NULL;
366
367                 state->reader_req = nb_packet_read_send(state, state->ev,
368                                                         state->reader);
369                 if (tevent_req_nomem(state->reader_req, req)) {
370                         return;
371                 }
372                 tevent_req_set_callback(
373                         state->reader_req, sock_packet_read_got_packet, req);
374                 return;
375         }
376
377         TALLOC_FREE(state->socket_req);
378         tevent_req_done(req);
379 }
380
381 static void sock_packet_read_got_socket(struct tevent_req *subreq)
382 {
383         struct tevent_req *req = tevent_req_callback_data(
384                 subreq, struct tevent_req);
385         struct sock_packet_read_state *state = tevent_req_data(
386                 req, struct sock_packet_read_state);
387         struct sockaddr_in *in_addr;
388         ssize_t received;
389         int err;
390
391         received = recvfrom_recv(subreq, &err);
392
393         TALLOC_FREE(state->socket_req);
394
395         if (received == -1) {
396                 if (state->reader_req != NULL) {
397                         /*
398                          * Still waiting for reader
399                          */
400                         return;
401                 }
402                 /*
403                  * Both socket and reader failed
404                  */
405                 tevent_req_nterror(req, map_nt_error_from_unix(err));
406                 return;
407         }
408         if (state->addr.ss_family != AF_INET) {
409                 goto retry;
410         }
411         in_addr = (struct sockaddr_in *)(void *)&state->addr;
412
413         state->packet = parse_packet((char *)state->buf, received, state->type,
414                                      in_addr->sin_addr, in_addr->sin_port);
415         if (state->packet == NULL) {
416                 DEBUG(10, ("parse_packet failed\n"));
417                 goto retry;
418         }
419         if ((state->trn_id != -1) &&
420             (state->trn_id != packet_trn_id(state->packet))) {
421                 DEBUG(10, ("Expected transaction id %d, got %d\n",
422                            state->trn_id, packet_trn_id(state->packet)));
423                 goto retry;
424         }
425
426         if ((state->validator != NULL) &&
427             !state->validator(state->packet, state->private_data)) {
428                 DEBUG(10, ("validator failed\n"));
429                 goto retry;
430         }
431
432         tevent_req_done(req);
433         return;
434
435 retry:
436         if (state->packet != NULL) {
437                 free_packet(state->packet);
438                 state->packet = NULL;
439         }
440         state->socket_req = recvfrom_send(state, state->ev, state->sock,
441                                           state->buf, sizeof(state->buf), 0,
442                                           &state->addr, &state->addr_len);
443         if (tevent_req_nomem(state->socket_req, req)) {
444                 return;
445         }
446         tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
447                                 req);
448 }
449
450 static NTSTATUS sock_packet_read_recv(struct tevent_req *req,
451                                       struct packet_struct **ppacket)
452 {
453         struct sock_packet_read_state *state = tevent_req_data(
454                 req, struct sock_packet_read_state);
455         NTSTATUS status;
456
457         if (tevent_req_is_nterror(req, &status)) {
458                 return status;
459         }
460         *ppacket = state->packet;
461         state->packet = NULL;
462         return NT_STATUS_OK;
463 }
464
465 struct nb_trans_state {
466         struct tevent_context *ev;
467         int sock;
468         struct nb_packet_reader *reader;
469
470         const struct sockaddr_storage *dst_addr;
471         uint8_t *buf;
472         size_t buflen;
473         enum packet_type type;
474         int trn_id;
475
476         bool (*validator)(struct packet_struct *p,
477                           void *private_data);
478         void *private_data;
479
480         struct packet_struct *packet;
481 };
482
483 static int nb_trans_state_destructor(struct nb_trans_state *s);
484 static void nb_trans_got_reader(struct tevent_req *subreq);
485 static void nb_trans_done(struct tevent_req *subreq);
486 static void nb_trans_sent(struct tevent_req *subreq);
487 static void nb_trans_send_next(struct tevent_req *subreq);
488
489 static struct tevent_req *nb_trans_send(
490         TALLOC_CTX *mem_ctx,
491         struct tevent_context *ev,
492         const struct sockaddr_storage *my_addr,
493         const struct sockaddr_storage *dst_addr,
494         bool bcast,
495         uint8_t *buf, size_t buflen,
496         enum packet_type type, int trn_id,
497         bool (*validator)(struct packet_struct *p,
498                           void *private_data),
499         void *private_data)
500 {
501         struct tevent_req *req, *subreq;
502         struct nb_trans_state *state;
503
504         req = tevent_req_create(mem_ctx, &state, struct nb_trans_state);
505         if (req == NULL) {
506                 return NULL;
507         }
508         talloc_set_destructor(state, nb_trans_state_destructor);
509         state->ev = ev;
510         state->dst_addr = dst_addr;
511         state->buf = buf;
512         state->buflen = buflen;
513         state->type = type;
514         state->trn_id = trn_id;
515         state->validator = validator;
516         state->private_data = private_data;
517
518         state->sock = open_socket_in(SOCK_DGRAM, 0, 3, my_addr, True);
519         if (state->sock == -1) {
520                 tevent_req_nterror(req, map_nt_error_from_unix(errno));
521                 DEBUG(10, ("open_socket_in failed: %s\n", strerror(errno)));
522                 return tevent_req_post(req, ev);
523         }
524
525         if (bcast) {
526                 set_socket_options(state->sock,"SO_BROADCAST");
527         }
528
529         subreq = nb_packet_reader_send(state, ev, type, state->trn_id, NULL);
530         if (tevent_req_nomem(subreq, req)) {
531                 return tevent_req_post(req, ev);
532         }
533         tevent_req_set_callback(subreq, nb_trans_got_reader, req);
534         return req;
535 }
536
537 static int nb_trans_state_destructor(struct nb_trans_state *s)
538 {
539         if (s->sock != -1) {
540                 close(s->sock);
541                 s->sock = -1;
542         }
543         if (s->packet != NULL) {
544                 free_packet(s->packet);
545                 s->packet = NULL;
546         }
547         return 0;
548 }
549
550 static void nb_trans_got_reader(struct tevent_req *subreq)
551 {
552         struct tevent_req *req = tevent_req_callback_data(
553                 subreq, struct tevent_req);
554         struct nb_trans_state *state = tevent_req_data(
555                 req, struct nb_trans_state);
556         NTSTATUS status;
557
558         status = nb_packet_reader_recv(subreq, state, &state->reader);
559         TALLOC_FREE(subreq);
560
561         if (!NT_STATUS_IS_OK(status)) {
562                 DEBUG(10, ("nmbd not around\n"));
563                 state->reader = NULL;
564         }
565
566         subreq = sock_packet_read_send(
567                 state, state->ev, state->sock,
568                 state->reader, state->type, state->trn_id,
569                 state->validator, state->private_data);
570         if (tevent_req_nomem(subreq, req)) {
571                 return;
572         }
573         tevent_req_set_callback(subreq, nb_trans_done, req);
574
575 #if !DEBUG_UNEXPECTED
576         subreq = sendto_send(state, state->ev, state->sock,
577                              state->buf, state->buflen, 0, state->dst_addr);
578         if (tevent_req_nomem(subreq, req)) {
579                 return;
580         }
581         tevent_req_set_callback(subreq, nb_trans_sent, req);
582 #endif
583 }
584
585 static void nb_trans_sent(struct tevent_req *subreq)
586 {
587         struct tevent_req *req = tevent_req_callback_data(
588                 subreq, struct tevent_req);
589         struct nb_trans_state *state = tevent_req_data(
590                 req, struct nb_trans_state);
591         ssize_t sent;
592         int err;
593
594         sent = sendto_recv(subreq, &err);
595         TALLOC_FREE(subreq);
596         if (sent == -1) {
597                 DEBUG(10, ("sendto failed: %s\n", strerror(err)));
598                 tevent_req_nterror(req, map_nt_error_from_unix(err));
599                 return;
600         }
601         subreq = tevent_wakeup_send(state, state->ev,
602                                     timeval_current_ofs(1, 0));
603         if (tevent_req_nomem(subreq, req)) {
604                 return;
605         }
606         tevent_req_set_callback(subreq, nb_trans_send_next, req);
607 }
608
609 static void nb_trans_send_next(struct tevent_req *subreq)
610 {
611         struct tevent_req *req = tevent_req_callback_data(
612                 subreq, struct tevent_req);
613         struct nb_trans_state *state = tevent_req_data(
614                 req, struct nb_trans_state);
615         bool ret;
616
617         ret = tevent_wakeup_recv(subreq);
618         TALLOC_FREE(subreq);
619         if (!ret) {
620                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
621                 return;
622         }
623         subreq = sendto_send(state, state->ev, state->sock,
624                              state->buf, state->buflen, 0, state->dst_addr);
625         if (tevent_req_nomem(subreq, req)) {
626                 return;
627         }
628         tevent_req_set_callback(subreq, nb_trans_sent, req);
629 }
630
631 static void nb_trans_done(struct tevent_req *subreq)
632 {
633         struct tevent_req *req = tevent_req_callback_data(
634                 subreq, struct tevent_req);
635         struct nb_trans_state *state = tevent_req_data(
636                 req, struct nb_trans_state);
637         NTSTATUS status;
638
639         status = sock_packet_read_recv(subreq, &state->packet);
640         TALLOC_FREE(subreq);
641         if (tevent_req_nterror(req, status)) {
642                 return;
643         }
644         tevent_req_done(req);
645 }
646
647 static NTSTATUS nb_trans_recv(struct tevent_req *req,
648                               struct packet_struct **ppacket)
649 {
650         struct nb_trans_state *state = tevent_req_data(
651                 req, struct nb_trans_state);
652         NTSTATUS status;
653
654         if (tevent_req_is_nterror(req, &status)) {
655                 return status;
656         }
657         *ppacket = state->packet;
658         state->packet = NULL;
659         return NT_STATUS_OK;
660 }
661
662 /****************************************************************************
663  Try and send a request to nmbd to send a packet_struct packet first.
664  If this fails, use send_packet().
665 **************************************************************************/
666
667 static bool send_packet_request(struct packet_struct *p)
668 {
669         struct messaging_context *msg_ctx = server_messaging_context();
670         if (msg_ctx) {
671                 pid_t nmbd_pid = pidfile_pid("nmbd");
672
673                 if (nmbd_pid) {
674                         /* Try nmbd. */
675                         if (NT_STATUS_IS_OK(messaging_send_buf(msg_ctx,
676                                         pid_to_procid(nmbd_pid),
677                                         MSG_SEND_PACKET,
678                                         (uint8_t *)p,
679                                         sizeof(struct packet_struct)))) {
680                                 return true;
681                         }
682                 }
683         }
684
685         return send_packet(p);
686 }
687
688 /****************************************************************************
689  Do a NBT node status query on an open socket and return an array of
690  structures holding the returned names or NULL if the query failed.
691 **************************************************************************/
692
693 struct node_status_query_state {
694         struct sockaddr_storage my_addr;
695         struct sockaddr_storage addr;
696         uint8_t buf[1024];
697         ssize_t buflen;
698         struct packet_struct *packet;
699 };
700
701 static int node_status_query_state_destructor(
702         struct node_status_query_state *s);
703 static bool node_status_query_validator(struct packet_struct *p,
704                                         void *private_data);
705 static void node_status_query_done(struct tevent_req *subreq);
706
707 struct tevent_req *node_status_query_send(TALLOC_CTX *mem_ctx,
708                                           struct tevent_context *ev,
709                                           struct nmb_name *name,
710                                           const struct sockaddr_storage *addr)
711 {
712         struct tevent_req *req, *subreq;
713         struct node_status_query_state *state;
714         struct packet_struct p;
715         struct nmb_packet *nmb = &p.packet.nmb;
716         struct sockaddr_in *in_addr;
717
718         req = tevent_req_create(mem_ctx, &state,
719                                 struct node_status_query_state);
720         if (req == NULL) {
721                 return NULL;
722         }
723         talloc_set_destructor(state, node_status_query_state_destructor);
724
725         if (addr->ss_family != AF_INET) {
726                 /* Can't do node status to IPv6 */
727                 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
728                 return tevent_req_post(req, ev);
729         }
730
731         state->addr = *addr;
732         in_addr = (struct sockaddr_in *)(void *)&state->addr;
733         in_addr->sin_port = htons(NMB_PORT);
734
735         if (!interpret_string_addr(&state->my_addr, lp_socket_address(),
736                                    AI_NUMERICHOST|AI_PASSIVE)) {
737                 zero_sockaddr(&state->my_addr);
738         }
739
740         ZERO_STRUCT(p);
741         nmb->header.name_trn_id = generate_trn_id();
742         nmb->header.opcode = 0;
743         nmb->header.response = false;
744         nmb->header.nm_flags.bcast = false;
745         nmb->header.nm_flags.recursion_available = false;
746         nmb->header.nm_flags.recursion_desired = false;
747         nmb->header.nm_flags.trunc = false;
748         nmb->header.nm_flags.authoritative = false;
749         nmb->header.rcode = 0;
750         nmb->header.qdcount = 1;
751         nmb->header.ancount = 0;
752         nmb->header.nscount = 0;
753         nmb->header.arcount = 0;
754         nmb->question.question_name = *name;
755         nmb->question.question_type = 0x21;
756         nmb->question.question_class = 0x1;
757
758 #if DEBUG_UNEXPECTED
759         p.ip = in_addr->sin_addr;
760         p.port = NMB_PORT;
761         p.recv_fd = -1;
762         p.send_fd = -1;
763         p.timestamp = time(NULL);
764         p.packet_type = NMB_PACKET;
765
766         {
767                 pid_t nmbd_pid = pidfile_pid("nmbd");
768
769                 if (nmbd_pid) {
770                         struct messaging_context *msg_ctx = messaging_init(
771                                 state, procid_self(), ev);
772                         /* Try nmbd. */
773                         messaging_send_buf(msg_ctx,
774                                            pid_to_procid(nmbd_pid),
775                                            MSG_SEND_PACKET,
776                                            (uint8_t *)&p,
777                                            sizeof(struct packet_struct));
778                         TALLOC_FREE(msg_ctx);
779                 }
780         }
781 #endif
782
783         state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
784                                      &p);
785         if (state->buflen == 0) {
786                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
787                 DEBUG(10, ("build_packet failed\n"));
788                 return tevent_req_post(req, ev);
789         }
790
791         subreq = nb_trans_send(state, ev, &state->my_addr, addr, false,
792                                state->buf, state->buflen,
793                                NMB_PACKET, nmb->header.name_trn_id,
794                                node_status_query_validator, NULL);
795         if (tevent_req_nomem(subreq, req)) {
796                 DEBUG(10, ("nb_trans_send failed\n"));
797                 return tevent_req_post(req, ev);
798         }
799         if (!tevent_req_set_endtime(req, ev, timeval_current_ofs(10, 0))) {
800                 return tevent_req_post(req, ev);
801         }
802         tevent_req_set_callback(subreq, node_status_query_done, req);
803         return req;
804 }
805
806 static bool node_status_query_validator(struct packet_struct *p,
807                                         void *private_data)
808 {
809         struct nmb_packet *nmb = &p->packet.nmb;
810         debug_nmb_packet(p);
811
812         if (nmb->header.opcode != 0 ||
813             nmb->header.nm_flags.bcast ||
814             nmb->header.rcode ||
815             !nmb->header.ancount ||
816             nmb->answers->rr_type != 0x21) {
817                 /*
818                  * XXXX what do we do with this? could be a redirect,
819                  * but we'll discard it for the moment
820                  */
821                 return false;
822         }
823         return true;
824 }
825
826 static int node_status_query_state_destructor(
827         struct node_status_query_state *s)
828 {
829         if (s->packet != NULL) {
830                 free_packet(s->packet);
831                 s->packet = NULL;
832         }
833         return 0;
834 }
835
836 static void node_status_query_done(struct tevent_req *subreq)
837 {
838         struct tevent_req *req = tevent_req_callback_data(
839                 subreq, struct tevent_req);
840         struct node_status_query_state *state = tevent_req_data(
841                 req, struct node_status_query_state);
842         NTSTATUS status;
843
844         status = nb_trans_recv(subreq, &state->packet);
845         TALLOC_FREE(subreq);
846         if (tevent_req_nterror(req, status)) {
847                 return;
848         }
849         tevent_req_done(req);
850 }
851
852 NTSTATUS node_status_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
853                                 struct node_status **pnode_status,
854                                 int *pnum_names,
855                                 struct node_status_extra *extra)
856 {
857         struct node_status_query_state *state = tevent_req_data(
858                 req, struct node_status_query_state);
859         struct node_status *node_status;
860         int num_names;
861         NTSTATUS status;
862
863         if (tevent_req_is_nterror(req, &status)) {
864                 return status;
865         }
866         node_status = parse_node_status(
867                 mem_ctx, &state->packet->packet.nmb.answers->rdata[0],
868                 &num_names, extra);
869         if (node_status == NULL) {
870                 return NT_STATUS_NO_MEMORY;
871         }
872         *pnode_status = node_status;
873         *pnum_names = num_names;
874         return NT_STATUS_OK;
875 }
876
877 NTSTATUS node_status_query(TALLOC_CTX *mem_ctx, struct nmb_name *name,
878                            const struct sockaddr_storage *addr,
879                            struct node_status **pnode_status,
880                            int *pnum_names,
881                            struct node_status_extra *extra)
882 {
883         TALLOC_CTX *frame = talloc_stackframe();
884         struct tevent_context *ev;
885         struct tevent_req *req;
886         NTSTATUS status = NT_STATUS_NO_MEMORY;
887
888         ev = tevent_context_init(frame);
889         if (ev == NULL) {
890                 goto fail;
891         }
892         req = node_status_query_send(ev, ev, name, addr);
893         if (req == NULL) {
894                 goto fail;
895         }
896         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
897                 goto fail;
898         }
899         status = node_status_query_recv(req, mem_ctx, pnode_status,
900                                         pnum_names, extra);
901  fail:
902         TALLOC_FREE(frame);
903         return status;
904 }
905
906 /****************************************************************************
907  Find the first type XX name in a node status reply - used for finding
908  a servers name given its IP. Return the matched name in *name.
909 **************************************************************************/
910
911 bool name_status_find(const char *q_name,
912                         int q_type,
913                         int type,
914                         const struct sockaddr_storage *to_ss,
915                         fstring name)
916 {
917         char addr[INET6_ADDRSTRLEN];
918         struct sockaddr_storage ss;
919         struct node_status *addrs = NULL;
920         struct nmb_name nname;
921         int count, i;
922         bool result = false;
923         NTSTATUS status;
924
925         if (lp_disable_netbios()) {
926                 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
927                                         q_name, q_type));
928                 return False;
929         }
930
931         print_sockaddr(addr, sizeof(addr), to_ss);
932
933         DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
934                    q_type, addr));
935
936         /* Check the cache first. */
937
938         if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
939                 return True;
940         }
941
942         if (to_ss->ss_family != AF_INET) {
943                 /* Can't do node status to IPv6 */
944                 return false;
945         }
946
947         if (!interpret_string_addr(&ss, lp_socket_address(),
948                                 AI_NUMERICHOST|AI_PASSIVE)) {
949                 zero_sockaddr(&ss);
950         }
951
952         /* W2K PDC's seem not to respond to '*'#0. JRA */
953         make_nmb_name(&nname, q_name, q_type);
954         status = node_status_query(talloc_tos(), &nname, to_ss,
955                                    &addrs, &count, NULL);
956         if (!NT_STATUS_IS_OK(status)) {
957                 goto done;
958         }
959
960         for (i=0;i<count;i++) {
961                 /* Find first one of the requested type that's not a GROUP. */
962                 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
963                         break;
964         }
965         if (i == count)
966                 goto done;
967
968         pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
969
970         /* Store the result in the cache. */
971         /* but don't store an entry for 0x1c names here.  Here we have
972            a single host and DOMAIN<0x1c> names should be a list of hosts */
973
974         if ( q_type != 0x1c ) {
975                 namecache_status_store(q_name, q_type, type, to_ss, name);
976         }
977
978         result = true;
979
980  done:
981         TALLOC_FREE(addrs);
982
983         DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
984
985         if (result)
986                 DEBUGADD(10, (", name %s ip address is %s", name, addr));
987
988         DEBUG(10, ("\n"));
989
990         return result;
991 }
992
993 /*
994   comparison function used by sort_addr_list
995 */
996
997 static int addr_compare(const struct sockaddr_storage *ss1,
998                         const struct sockaddr_storage *ss2)
999 {
1000         int max_bits1=0, max_bits2=0;
1001         int num_interfaces = iface_count();
1002         int i;
1003
1004         /* Sort IPv4 addresses first. */
1005         if (ss1->ss_family != ss2->ss_family) {
1006                 if (ss2->ss_family == AF_INET) {
1007                         return 1;
1008                 } else {
1009                         return -1;
1010                 }
1011         }
1012
1013         /* Here we know both addresses are of the same
1014          * family. */
1015
1016         for (i=0;i<num_interfaces;i++) {
1017                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1018                 unsigned char *p_ss1 = NULL;
1019                 unsigned char *p_ss2 = NULL;
1020                 unsigned char *p_if = NULL;
1021                 size_t len = 0;
1022                 int bits1, bits2;
1023
1024                 if (pss->ss_family != ss1->ss_family) {
1025                         /* Ignore interfaces of the wrong type. */
1026                         continue;
1027                 }
1028                 if (pss->ss_family == AF_INET) {
1029                         p_if = (unsigned char *)
1030                                 &((const struct sockaddr_in *)pss)->sin_addr;
1031                         p_ss1 = (unsigned char *)
1032                                 &((const struct sockaddr_in *)ss1)->sin_addr;
1033                         p_ss2 = (unsigned char *)
1034                                 &((const struct sockaddr_in *)ss2)->sin_addr;
1035                         len = 4;
1036                 }
1037 #if defined(HAVE_IPV6)
1038                 if (pss->ss_family == AF_INET6) {
1039                         p_if = (unsigned char *)
1040                                 &((const struct sockaddr_in6 *)pss)->sin6_addr;
1041                         p_ss1 = (unsigned char *)
1042                                 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
1043                         p_ss2 = (unsigned char *)
1044                                 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
1045                         len = 16;
1046                 }
1047 #endif
1048                 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
1049                         continue;
1050                 }
1051                 bits1 = matching_len_bits(p_ss1, p_if, len);
1052                 bits2 = matching_len_bits(p_ss2, p_if, len);
1053                 max_bits1 = MAX(bits1, max_bits1);
1054                 max_bits2 = MAX(bits2, max_bits2);
1055         }
1056
1057         /* Bias towards directly reachable IPs */
1058         if (iface_local((struct sockaddr *)ss1)) {
1059                 if (ss1->ss_family == AF_INET) {
1060                         max_bits1 += 32;
1061                 } else {
1062                         max_bits1 += 128;
1063                 }
1064         }
1065         if (iface_local((struct sockaddr *)ss2)) {
1066                 if (ss2->ss_family == AF_INET) {
1067                         max_bits2 += 32;
1068                 } else {
1069                         max_bits2 += 128;
1070                 }
1071         }
1072         return max_bits2 - max_bits1;
1073 }
1074
1075 /*******************************************************************
1076  compare 2 ldap IPs by nearness to our interfaces - used in qsort
1077 *******************************************************************/
1078
1079 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
1080 {
1081         int result;
1082
1083         if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
1084                 return result;
1085         }
1086
1087         if (ss1->port > ss2->port) {
1088                 return 1;
1089         }
1090
1091         if (ss1->port < ss2->port) {
1092                 return -1;
1093         }
1094
1095         return 0;
1096 }
1097
1098 /*
1099   sort an IP list so that names that are close to one of our interfaces
1100   are at the top. This prevents the problem where a WINS server returns an IP
1101   that is not reachable from our subnet as the first match
1102 */
1103
1104 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
1105 {
1106         if (count <= 1) {
1107                 return;
1108         }
1109
1110         TYPESAFE_QSORT(sslist, count, addr_compare);
1111 }
1112
1113 static void sort_service_list(struct ip_service *servlist, int count)
1114 {
1115         if (count <= 1) {
1116                 return;
1117         }
1118
1119         TYPESAFE_QSORT(servlist, count, ip_service_compare);
1120 }
1121
1122 /**********************************************************************
1123  Remove any duplicate address/port pairs in the list
1124  *********************************************************************/
1125
1126 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
1127 {
1128         int i, j;
1129
1130         DEBUG(10,("remove_duplicate_addrs2: "
1131                         "looking for duplicate address/port pairs\n"));
1132
1133         /* one loop to remove duplicates */
1134         for ( i=0; i<count; i++ ) {
1135                 if ( is_zero_addr((struct sockaddr *)&iplist[i].ss)) {
1136                         continue;
1137                 }
1138
1139                 for ( j=i+1; j<count; j++ ) {
1140                         if (sockaddr_equal((struct sockaddr *)&iplist[i].ss, (struct sockaddr *)&iplist[j].ss) &&
1141                                         iplist[i].port == iplist[j].port) {
1142                                 zero_sockaddr(&iplist[j].ss);
1143                         }
1144                 }
1145         }
1146
1147         /* one loop to clean up any holes we left */
1148         /* first ip should never be a zero_ip() */
1149         for (i = 0; i<count; ) {
1150                 if (is_zero_addr((struct sockaddr *)&iplist[i].ss) ) {
1151                         if (i != count-1) {
1152                                 memmove(&iplist[i], &iplist[i+1],
1153                                         (count - i - 1)*sizeof(iplist[i]));
1154                         }
1155                         count--;
1156                         continue;
1157                 }
1158                 i++;
1159         }
1160
1161         return count;
1162 }
1163
1164 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1165 {
1166         TALLOC_CTX *frame = talloc_stackframe();
1167         struct ip_service *iplist_new = TALLOC_ARRAY(frame, struct ip_service, count);
1168         int i, j;
1169
1170         if (iplist_new == NULL) {
1171                 TALLOC_FREE(frame);
1172                 return false;
1173         }
1174
1175         j = 0;
1176
1177         /* Copy IPv4 first. */
1178         for (i = 0; i < count; i++) {
1179                 if (iplist[i].ss.ss_family == AF_INET) {
1180                         iplist_new[j++] = iplist[i];
1181                 }
1182         }
1183
1184         /* Copy IPv6. */
1185         for (i = 0; i < count; i++) {
1186                 if (iplist[i].ss.ss_family != AF_INET) {
1187                         iplist_new[j++] = iplist[i];
1188                 }
1189         }
1190
1191         memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1192         TALLOC_FREE(frame);
1193         return true;
1194 }
1195
1196 /****************************************************************************
1197  Do a netbios name query to find someones IP.
1198  Returns an array of IP addresses or NULL if none.
1199  *count will be set to the number of addresses returned.
1200  *timed_out is set if we failed by timing out
1201 ****************************************************************************/
1202
1203 NTSTATUS name_query(int fd,
1204                         const char *name,
1205                         int name_type,
1206                         bool bcast,
1207                         bool recurse,
1208                         const struct sockaddr_storage *to_ss,
1209                         TALLOC_CTX *mem_ctx,
1210                         struct sockaddr_storage **addrs,
1211                         int *count,
1212                         int *flags,
1213                         bool *timed_out)
1214 {
1215         bool found=false;
1216         int i, retries = 3;
1217         int retry_time = bcast?250:2000;
1218         struct timespec tp;
1219         struct packet_struct p;
1220         struct packet_struct *p2;
1221         struct nmb_packet *nmb = &p.packet.nmb;
1222         struct sockaddr_storage *ss_list = NULL;
1223
1224         if (lp_disable_netbios()) {
1225                 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1226                                         name, name_type));
1227                 return NT_STATUS_NOT_FOUND;
1228         }
1229
1230         if (to_ss->ss_family != AF_INET) {
1231                 return NT_STATUS_INVALID_ADDRESS;
1232         }
1233
1234         if (timed_out) {
1235                 *timed_out = false;
1236         }
1237
1238         memset((char *)&p,'\0',sizeof(p));
1239         (*count) = 0;
1240         (*flags) = 0;
1241
1242         nmb->header.name_trn_id = generate_trn_id();
1243         nmb->header.opcode = 0;
1244         nmb->header.response = false;
1245         nmb->header.nm_flags.bcast = bcast;
1246         nmb->header.nm_flags.recursion_available = false;
1247         nmb->header.nm_flags.recursion_desired = recurse;
1248         nmb->header.nm_flags.trunc = false;
1249         nmb->header.nm_flags.authoritative = false;
1250         nmb->header.rcode = 0;
1251         nmb->header.qdcount = 1;
1252         nmb->header.ancount = 0;
1253         nmb->header.nscount = 0;
1254         nmb->header.arcount = 0;
1255
1256         make_nmb_name(&nmb->question.question_name,name,name_type);
1257
1258         nmb->question.question_type = 0x20;
1259         nmb->question.question_class = 0x1;
1260
1261         p.ip = ((struct sockaddr_in *)to_ss)->sin_addr;
1262         p.port = NMB_PORT;
1263         p.recv_fd = -1;
1264         p.send_fd = fd;
1265         p.timestamp = time(NULL);
1266         p.packet_type = NMB_PACKET;
1267
1268         clock_gettime_mono(&tp);
1269
1270         if (!send_packet_request(&p))
1271                 return NT_STATUS_NOT_FOUND;
1272
1273         retries--;
1274
1275         while (1) {
1276                 struct timespec tp2;
1277
1278                 clock_gettime_mono(&tp2);
1279                 if (nsec_time_diff(&tp2,&tp)/1000000 > retry_time) {
1280                         if (!retries)
1281                                 break;
1282                         if (!found && !send_packet_request(&p))
1283                                 return NT_STATUS_NOT_FOUND;
1284                         clock_gettime_mono(&tp);
1285                         retries--;
1286                 }
1287                 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
1288                         struct nmb_packet *nmb2 = &p2->packet.nmb;
1289                         debug_nmb_packet(p2);
1290
1291                         /* If we get a Negative Name Query Response from a WINS
1292                          * server, we should report it and give up.
1293                          */
1294                         if( 0 == nmb2->header.opcode    /* A query response   */
1295                             && !(bcast)                 /* from a WINS server */
1296                             && nmb2->header.rcode       /* Error returned     */
1297                                 ) {
1298
1299                                 if( DEBUGLVL( 3 ) ) {
1300                                         /* Only executed if DEBUGLEVEL >= 3 */
1301                                         dbgtext( "Negative name query "
1302                                                 "response, rcode 0x%02x: ",
1303                                                 nmb2->header.rcode );
1304                                         switch( nmb2->header.rcode ) {
1305                                         case 0x01:
1306                                                 dbgtext( "Request "
1307                                                 "was invalidly formatted.\n" );
1308                                                 break;
1309                                         case 0x02:
1310                                                 dbgtext( "Problem with NBNS, "
1311                                                 "cannot process name.\n");
1312                                                 break;
1313                                         case 0x03:
1314                                                 dbgtext( "The name requested "
1315                                                 "does not exist.\n" );
1316                                                 break;
1317                                         case 0x04:
1318                                                 dbgtext( "Unsupported request "
1319                                                 "error.\n" );
1320                                                 break;
1321                                         case 0x05:
1322                                                 dbgtext( "Query refused "
1323                                                 "error.\n" );
1324                                                 break;
1325                                         default:
1326                                                 dbgtext( "Unrecognized error "
1327                                                 "code.\n" );
1328                                                 break;
1329                                         }
1330                                 }
1331                                 free_packet(p2);
1332                                 return NT_STATUS_NOT_FOUND;
1333                         }
1334
1335                         if (nmb2->header.opcode != 0 ||
1336                             nmb2->header.nm_flags.bcast ||
1337                             nmb2->header.rcode ||
1338                             !nmb2->header.ancount) {
1339                                 /*
1340                                  * XXXX what do we do with this? Could be a
1341                                  * redirect, but we'll discard it for the
1342                                  * moment.
1343                                  */
1344                                 free_packet(p2);
1345                                 continue;
1346                         }
1347
1348                         ss_list = TALLOC_REALLOC_ARRAY(mem_ctx, ss_list,
1349                                                 struct sockaddr_storage,
1350                                                 (*count) +
1351                                                 nmb2->answers->rdlength/6);
1352
1353                         if (!ss_list) {
1354                                 DEBUG(0,("name_query: Realloc failed.\n"));
1355                                 free_packet(p2);
1356                                 return NT_STATUS_NO_MEMORY;
1357                         }
1358
1359                         DEBUG(2,("Got a positive name query response "
1360                                         "from %s ( ",
1361                                         inet_ntoa(p2->ip)));
1362
1363                         for (i=0;i<nmb2->answers->rdlength/6;i++) {
1364                                 struct in_addr ip;
1365                                 putip((char *)&ip,&nmb2->answers->rdata[2+i*6]);
1366                                 in_addr_to_sockaddr_storage(&ss_list[(*count)],
1367                                                 ip);
1368                                 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1369                                 (*count)++;
1370                         }
1371                         DEBUGADD(2,(")\n"));
1372
1373                         found=true;
1374                         retries=0;
1375                         /* We add the flags back ... */
1376                         if (nmb2->header.response)
1377                                 (*flags) |= NM_FLAGS_RS;
1378                         if (nmb2->header.nm_flags.authoritative)
1379                                 (*flags) |= NM_FLAGS_AA;
1380                         if (nmb2->header.nm_flags.trunc)
1381                                 (*flags) |= NM_FLAGS_TC;
1382                         if (nmb2->header.nm_flags.recursion_desired)
1383                                 (*flags) |= NM_FLAGS_RD;
1384                         if (nmb2->header.nm_flags.recursion_available)
1385                                 (*flags) |= NM_FLAGS_RA;
1386                         if (nmb2->header.nm_flags.bcast)
1387                                 (*flags) |= NM_FLAGS_B;
1388                         free_packet(p2);
1389                         /*
1390                          * If we're doing a unicast lookup we only
1391                          * expect one reply. Don't wait the full 2
1392                          * seconds if we got one. JRA.
1393                          */
1394                         if(!bcast && found)
1395                                 break;
1396                 }
1397         }
1398
1399         /* only set timed_out if we didn't fund what we where looking for*/
1400
1401         if ( !found && timed_out ) {
1402                 *timed_out = true;
1403         }
1404
1405         /* sort the ip list so we choose close servers first if possible */
1406         sort_addr_list(ss_list, *count);
1407
1408         *addrs = ss_list;
1409         return NT_STATUS_OK;
1410 }
1411
1412 /********************************************************
1413  convert an array if struct sockaddr_storage to struct ip_service
1414  return false on failure.  Port is set to PORT_NONE;
1415 *********************************************************/
1416
1417 static bool convert_ss2service(struct ip_service **return_iplist,
1418                 const struct sockaddr_storage *ss_list,
1419                 int count)
1420 {
1421         int i;
1422
1423         if ( count==0 || !ss_list )
1424                 return False;
1425
1426         /* copy the ip address; port will be PORT_NONE */
1427         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
1428                         NULL) {
1429                 DEBUG(0,("convert_ip2service: malloc failed "
1430                         "for %d enetries!\n", count ));
1431                 return False;
1432         }
1433
1434         for ( i=0; i<count; i++ ) {
1435                 (*return_iplist)[i].ss   = ss_list[i];
1436                 (*return_iplist)[i].port = PORT_NONE;
1437         }
1438
1439         return true;
1440 }
1441
1442 /********************************************************
1443  Resolve via "bcast" method.
1444 *********************************************************/
1445
1446 NTSTATUS name_resolve_bcast(const char *name,
1447                         int name_type,
1448                         struct ip_service **return_iplist,
1449                         int *return_count)
1450 {
1451         int sock, i;
1452         int num_interfaces = iface_count();
1453         struct sockaddr_storage *ss_list;
1454         struct sockaddr_storage ss;
1455         NTSTATUS status = NT_STATUS_NOT_FOUND;
1456
1457         if (lp_disable_netbios()) {
1458                 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1459                                         name, name_type));
1460                 return NT_STATUS_INVALID_PARAMETER;
1461         }
1462
1463         *return_iplist = NULL;
1464         *return_count = 0;
1465
1466         /*
1467          * "bcast" means do a broadcast lookup on all the local interfaces.
1468          */
1469
1470         DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
1471                 "for name %s<0x%x>\n", name, name_type));
1472
1473         if (!interpret_string_addr(&ss, lp_socket_address(),
1474                                 AI_NUMERICHOST|AI_PASSIVE)) {
1475                 zero_sockaddr(&ss);
1476         }
1477
1478         sock = open_socket_in( SOCK_DGRAM, 0, 3, &ss, true );
1479         if (sock == -1) {
1480                 return map_nt_error_from_unix(errno);
1481         }
1482
1483         set_socket_options(sock,"SO_BROADCAST");
1484         /*
1485          * Lookup the name on all the interfaces, return on
1486          * the first successful match.
1487          */
1488         for( i = num_interfaces-1; i >= 0; i--) {
1489                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1490                 int flags;
1491
1492                 /* Done this way to fix compiler error on IRIX 5.x */
1493                 if (!pss) {
1494                         continue;
1495                 }
1496                 status = name_query(sock, name, name_type, true, true, pss,
1497                                     talloc_tos(), &ss_list, return_count,
1498                                     &flags, NULL);
1499                 if (NT_STATUS_IS_OK(status)) {
1500                         goto success;
1501                 }
1502         }
1503
1504         /* failed - no response */
1505
1506         close(sock);
1507         return status;
1508
1509 success:
1510
1511         if (!convert_ss2service(return_iplist, ss_list, *return_count) )
1512                 status = NT_STATUS_NO_MEMORY;
1513
1514         TALLOC_FREE(ss_list);
1515         close(sock);
1516         return status;
1517 }
1518
1519 /********************************************************
1520  Resolve via "wins" method.
1521 *********************************************************/
1522
1523 NTSTATUS resolve_wins(const char *name,
1524                 int name_type,
1525                 struct ip_service **return_iplist,
1526                 int *return_count)
1527 {
1528         int sock, t, i;
1529         char **wins_tags;
1530         struct sockaddr_storage src_ss, *ss_list = NULL;
1531         struct in_addr src_ip;
1532         NTSTATUS status;
1533
1534         if (lp_disable_netbios()) {
1535                 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1536                                         name, name_type));
1537                 return NT_STATUS_INVALID_PARAMETER;
1538         }
1539
1540         *return_iplist = NULL;
1541         *return_count = 0;
1542
1543         DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1544                                 name, name_type));
1545
1546         if (wins_srv_count() < 1) {
1547                 DEBUG(3,("resolve_wins: WINS server resolution selected "
1548                         "and no WINS servers listed.\n"));
1549                 return NT_STATUS_INVALID_PARAMETER;
1550         }
1551
1552         /* we try a lookup on each of the WINS tags in turn */
1553         wins_tags = wins_srv_tags();
1554
1555         if (!wins_tags) {
1556                 /* huh? no tags?? give up in disgust */
1557                 return NT_STATUS_INVALID_PARAMETER;
1558         }
1559
1560         /* the address we will be sending from */
1561         if (!interpret_string_addr(&src_ss, lp_socket_address(),
1562                                 AI_NUMERICHOST|AI_PASSIVE)) {
1563                 zero_sockaddr(&src_ss);
1564         }
1565
1566         if (src_ss.ss_family != AF_INET) {
1567                 char addr[INET6_ADDRSTRLEN];
1568                 print_sockaddr(addr, sizeof(addr), &src_ss);
1569                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1570                         "on IPv6 address %s\n",
1571                         addr));
1572                 wins_srv_tags_free(wins_tags);
1573                 return NT_STATUS_INVALID_PARAMETER;
1574         }
1575
1576         src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1577
1578         /* in the worst case we will try every wins server with every
1579            tag! */
1580         for (t=0; wins_tags && wins_tags[t]; t++) {
1581                 int srv_count = wins_srv_count_tag(wins_tags[t]);
1582                 for (i=0; i<srv_count; i++) {
1583                         struct sockaddr_storage wins_ss;
1584                         struct in_addr wins_ip;
1585                         int flags;
1586                         bool timed_out;
1587
1588                         wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1589
1590                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
1591                                 /* yikes! we'll loop forever */
1592                                 continue;
1593                         }
1594
1595                         /* skip any that have been unresponsive lately */
1596                         if (wins_srv_is_dead(wins_ip, src_ip)) {
1597                                 continue;
1598                         }
1599
1600                         DEBUG(3,("resolve_wins: using WINS server %s "
1601                                 "and tag '%s'\n",
1602                                 inet_ntoa(wins_ip), wins_tags[t]));
1603
1604                         sock = open_socket_in(SOCK_DGRAM, 0, 3, &src_ss, true);
1605                         if (sock == -1) {
1606                                 continue;
1607                         }
1608
1609                         in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1610                         status = name_query(sock,
1611                                                 name,
1612                                                 name_type,
1613                                                 false,
1614                                                 true,
1615                                                 &wins_ss,
1616                                                 talloc_tos(),
1617                                                 &ss_list,
1618                                                 return_count,
1619                                                 &flags,
1620                                                 &timed_out);
1621
1622                         /* exit loop if we got a list of addresses */
1623
1624                         if (NT_STATUS_IS_OK(status)) {
1625                                 goto success;
1626                         }
1627
1628                         close(sock);
1629
1630                         if (timed_out) {
1631                                 /* Timed out waiting for WINS server to
1632                                  * respond.
1633                                  * Mark it dead. */
1634                                 wins_srv_died(wins_ip, src_ip);
1635                         } else {
1636                                 /* The name definitely isn't in this
1637                                    group of WINS servers.
1638                                    goto the next group  */
1639                                 break;
1640                         }
1641                 }
1642         }
1643
1644         wins_srv_tags_free(wins_tags);
1645         return NT_STATUS_NO_LOGON_SERVERS;
1646
1647 success:
1648
1649         status = NT_STATUS_OK;
1650         if (!convert_ss2service(return_iplist, ss_list, *return_count))
1651                 status = NT_STATUS_INVALID_PARAMETER;
1652
1653         TALLOC_FREE(ss_list);
1654         wins_srv_tags_free(wins_tags);
1655         close(sock);
1656
1657         return status;
1658 }
1659
1660 /********************************************************
1661  Resolve via "lmhosts" method.
1662 *********************************************************/
1663
1664 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1665                                 struct ip_service **return_iplist,
1666                                 int *return_count)
1667 {
1668         /*
1669          * "lmhosts" means parse the local lmhosts file.
1670          */
1671         struct sockaddr_storage *ss_list;
1672         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1673         TALLOC_CTX *ctx = NULL;
1674
1675         *return_iplist = NULL;
1676         *return_count = 0;
1677
1678         DEBUG(3,("resolve_lmhosts: "
1679                 "Attempting lmhosts lookup for name %s<0x%x>\n",
1680                 name, name_type));
1681
1682         ctx = talloc_init("resolve_lmhosts");
1683         if (!ctx) {
1684                 return NT_STATUS_NO_MEMORY;
1685         }
1686
1687         status = resolve_lmhosts_file_as_sockaddr(get_dyn_LMHOSTSFILE(), 
1688                                                   name, name_type, 
1689                                                   ctx, 
1690                                                   &ss_list, 
1691                                                   return_count);
1692         if (NT_STATUS_IS_OK(status)) {
1693                 if (convert_ss2service(return_iplist, 
1694                                        ss_list,
1695                                        *return_count)) {
1696                         talloc_free(ctx);
1697                         return NT_STATUS_OK;
1698                 } else {
1699                         talloc_free(ctx);
1700                         return NT_STATUS_NO_MEMORY;
1701                 }
1702         }
1703         talloc_free(ctx);
1704         return status;
1705 }
1706
1707
1708 /********************************************************
1709  Resolve via "hosts" method.
1710 *********************************************************/
1711
1712 static NTSTATUS resolve_hosts(const char *name, int name_type,
1713                               struct ip_service **return_iplist,
1714                               int *return_count)
1715 {
1716         /*
1717          * "host" means do a localhost, or dns lookup.
1718          */
1719         struct addrinfo hints;
1720         struct addrinfo *ailist = NULL;
1721         struct addrinfo *res = NULL;
1722         int ret = -1;
1723         int i = 0;
1724
1725         if ( name_type != 0x20 && name_type != 0x0) {
1726                 DEBUG(5, ("resolve_hosts: not appropriate "
1727                         "for name type <0x%x>\n",
1728                         name_type));
1729                 return NT_STATUS_INVALID_PARAMETER;
1730         }
1731
1732         *return_iplist = NULL;
1733         *return_count = 0;
1734
1735         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1736                                 name, name_type));
1737
1738         ZERO_STRUCT(hints);
1739         /* By default make sure it supports TCP. */
1740         hints.ai_socktype = SOCK_STREAM;
1741         hints.ai_flags = AI_ADDRCONFIG;
1742
1743 #if !defined(HAVE_IPV6)
1744         /* Unless we have IPv6, we really only want IPv4 addresses back. */
1745         hints.ai_family = AF_INET;
1746 #endif
1747
1748         ret = getaddrinfo(name,
1749                         NULL,
1750                         &hints,
1751                         &ailist);
1752         if (ret) {
1753                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1754                         name,
1755                         gai_strerror(ret) ));
1756         }
1757
1758         for (res = ailist; res; res = res->ai_next) {
1759                 struct sockaddr_storage ss;
1760
1761                 if (!res->ai_addr || res->ai_addrlen == 0) {
1762                         continue;
1763                 }
1764
1765                 ZERO_STRUCT(ss);
1766                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1767
1768                 *return_count += 1;
1769
1770                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1771                                                 struct ip_service,
1772                                                 *return_count);
1773                 if (!*return_iplist) {
1774                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
1775                         freeaddrinfo(ailist);
1776                         return NT_STATUS_NO_MEMORY;
1777                 }
1778                 (*return_iplist)[i].ss = ss;
1779                 (*return_iplist)[i].port = PORT_NONE;
1780                 i++;
1781         }
1782         if (ailist) {
1783                 freeaddrinfo(ailist);
1784         }
1785         if (*return_count) {
1786                 return NT_STATUS_OK;
1787         }
1788         return NT_STATUS_UNSUCCESSFUL;
1789 }
1790
1791 /********************************************************
1792  Resolve via "ADS" method.
1793 *********************************************************/
1794
1795 static NTSTATUS resolve_ads(const char *name,
1796                             int name_type,
1797                             const char *sitename,
1798                             struct ip_service **return_iplist,
1799                             int *return_count)
1800 {
1801         int                     i, j;
1802         NTSTATUS                status;
1803         TALLOC_CTX              *ctx;
1804         struct dns_rr_srv       *dcs = NULL;
1805         int                     numdcs = 0;
1806         int                     numaddrs = 0;
1807
1808         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1809             (name_type != 0x1b)) {
1810                 return NT_STATUS_INVALID_PARAMETER;
1811         }
1812
1813         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1814                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1815                 return NT_STATUS_NO_MEMORY;
1816         }
1817
1818         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1819
1820         switch (name_type) {
1821                 case 0x1b:
1822                         DEBUG(5,("resolve_ads: Attempting to resolve "
1823                                  "PDC for %s using DNS\n", name));
1824                         status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1825                         break;
1826
1827                 case 0x1c:
1828                         DEBUG(5,("resolve_ads: Attempting to resolve "
1829                                  "DCs for %s using DNS\n", name));
1830                         status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1831                                                    &numdcs);
1832                         break;
1833                 case KDC_NAME_TYPE:
1834                         DEBUG(5,("resolve_ads: Attempting to resolve "
1835                                  "KDCs for %s using DNS\n", name));
1836                         status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1837                                                     &numdcs);
1838                         break;
1839                 default:
1840                         status = NT_STATUS_INVALID_PARAMETER;
1841                         break;
1842         }
1843
1844         if ( !NT_STATUS_IS_OK( status ) ) {
1845                 talloc_destroy(ctx);
1846                 return status;
1847         }
1848
1849         for (i=0;i<numdcs;i++) {
1850                 numaddrs += MAX(dcs[i].num_ips,1);
1851         }
1852
1853         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1854                         NULL ) {
1855                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1856                                         numaddrs ));
1857                 talloc_destroy(ctx);
1858                 return NT_STATUS_NO_MEMORY;
1859         }
1860
1861         /* now unroll the list of IP addresses */
1862
1863         *return_count = 0;
1864         i = 0;
1865         j = 0;
1866         while ( i < numdcs && (*return_count<numaddrs) ) {
1867                 struct ip_service *r = &(*return_iplist)[*return_count];
1868
1869                 r->port = dcs[i].port;
1870
1871                 /* If we don't have an IP list for a name, lookup it up */
1872
1873                 if (!dcs[i].ss_s) {
1874                         interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1875                         i++;
1876                         j = 0;
1877                 } else {
1878                         /* use the IP addresses from the SRV sresponse */
1879
1880                         if ( j >= dcs[i].num_ips ) {
1881                                 i++;
1882                                 j = 0;
1883                                 continue;
1884                         }
1885
1886                         r->ss = dcs[i].ss_s[j];
1887                         j++;
1888                 }
1889
1890                 /* make sure it is a valid IP.  I considered checking the
1891                  * negative connection cache, but this is the wrong place
1892                  * for it. Maybe only as a hack. After think about it, if
1893                  * all of the IP addresses returned from DNS are dead, what
1894                  * hope does a netbios name lookup have ? The standard reason
1895                  * for falling back to netbios lookups is that our DNS server
1896                  * doesn't know anything about the DC's   -- jerry */
1897
1898                 if (!is_zero_addr((struct sockaddr *)&r->ss)) {
1899                         (*return_count)++;
1900                 }
1901         }
1902
1903         talloc_destroy(ctx);
1904         return NT_STATUS_OK;
1905 }
1906
1907 /*******************************************************************
1908  Internal interface to resolve a name into an IP address.
1909  Use this function if the string is either an IP address, DNS
1910  or host name or NetBIOS name. This uses the name switch in the
1911  smb.conf to determine the order of name resolution.
1912
1913  Added support for ip addr/port to support ADS ldap servers.
1914  the only place we currently care about the port is in the
1915  resolve_hosts() when looking up DC's via SRV RR entries in DNS
1916 **********************************************************************/
1917
1918 NTSTATUS internal_resolve_name(const char *name,
1919                                 int name_type,
1920                                 const char *sitename,
1921                                 struct ip_service **return_iplist,
1922                                 int *return_count,
1923                                 const char *resolve_order)
1924 {
1925         char *tok;
1926         const char *ptr;
1927         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1928         int i;
1929         TALLOC_CTX *frame = NULL;
1930
1931         *return_iplist = NULL;
1932         *return_count = 0;
1933
1934         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1935                         name, name_type, sitename ? sitename : "(null)"));
1936
1937         if (is_ipaddress(name)) {
1938                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1939                                 NULL) {
1940                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1941                         return NT_STATUS_NO_MEMORY;
1942                 }
1943
1944                 /* ignore the port here */
1945                 (*return_iplist)->port = PORT_NONE;
1946
1947                 /* if it's in the form of an IP address then get the lib to interpret it */
1948                 if (!interpret_string_addr(&(*return_iplist)->ss,
1949                                         name, AI_NUMERICHOST)) {
1950                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
1951                                 "failed on %s\n",
1952                                 name));
1953                         SAFE_FREE(*return_iplist);
1954                         return NT_STATUS_INVALID_PARAMETER;
1955                 }
1956                 *return_count = 1;
1957                 return NT_STATUS_OK;
1958         }
1959
1960         /* Check name cache */
1961
1962         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1963                 /* This could be a negative response */
1964                 if (*return_count > 0) {
1965                         return NT_STATUS_OK;
1966                 } else {
1967                         return NT_STATUS_UNSUCCESSFUL;
1968                 }
1969         }
1970
1971         /* set the name resolution order */
1972
1973         if (strcmp( resolve_order, "NULL") == 0) {
1974                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1975                 return NT_STATUS_INVALID_PARAMETER;
1976         }
1977
1978         if (!resolve_order[0]) {
1979                 ptr = "host";
1980         } else {
1981                 ptr = resolve_order;
1982         }
1983
1984         /* iterate through the name resolution backends */
1985
1986         frame = talloc_stackframe();
1987         while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
1988                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1989                         status = resolve_hosts(name, name_type, return_iplist,
1990                                                return_count);
1991                         if (NT_STATUS_IS_OK(status)) {
1992                                 goto done;
1993                         }
1994                 } else if(strequal( tok, "kdc")) {
1995                         /* deal with KDC_NAME_TYPE names here.
1996                          * This will result in a SRV record lookup */
1997                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1998                                              return_iplist, return_count);
1999                         if (NT_STATUS_IS_OK(status)) {
2000                                 /* Ensure we don't namecache
2001                                  * this with the KDC port. */
2002                                 name_type = KDC_NAME_TYPE;
2003                                 goto done;
2004                         }
2005                 } else if(strequal( tok, "ads")) {
2006                         /* deal with 0x1c and 0x1b names here.
2007                          * This will result in a SRV record lookup */
2008                         status = resolve_ads(name, name_type, sitename,
2009                                              return_iplist, return_count);
2010                         if (NT_STATUS_IS_OK(status)) {
2011                                 goto done;
2012                         }
2013                 } else if(strequal( tok, "lmhosts")) {
2014                         status = resolve_lmhosts(name, name_type,
2015                                                  return_iplist, return_count);
2016                         if (NT_STATUS_IS_OK(status)) {
2017                                 goto done;
2018                         }
2019                 } else if(strequal( tok, "wins")) {
2020                         /* don't resolve 1D via WINS */
2021                         if (name_type != 0x1D) {
2022                                 status = resolve_wins(name, name_type,
2023                                                       return_iplist,
2024                                                       return_count);
2025                                 if (NT_STATUS_IS_OK(status)) {
2026                                         goto done;
2027                                 }
2028                         }
2029                 } else if(strequal( tok, "bcast")) {
2030                         status = name_resolve_bcast(name, name_type,
2031                                                     return_iplist,
2032                                                     return_count);
2033                         if (NT_STATUS_IS_OK(status)) {
2034                                 goto done;
2035                         }
2036                 } else {
2037                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
2038                                 tok));
2039                 }
2040         }
2041
2042         /* All of the resolve_* functions above have returned false. */
2043
2044         TALLOC_FREE(frame);
2045         SAFE_FREE(*return_iplist);
2046         *return_count = 0;
2047
2048         return NT_STATUS_UNSUCCESSFUL;
2049
2050   done:
2051
2052         /* Remove duplicate entries.  Some queries, notably #1c (domain
2053         controllers) return the PDC in iplist[0] and then all domain
2054         controllers including the PDC in iplist[1..n].  Iterating over
2055         the iplist when the PDC is down will cause two sets of timeouts. */
2056
2057         if ( *return_count ) {
2058                 *return_count = remove_duplicate_addrs2(*return_iplist,
2059                                         *return_count );
2060         }
2061
2062         /* Save in name cache */
2063         if ( DEBUGLEVEL >= 100 ) {
2064                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
2065                         char addr[INET6_ADDRSTRLEN];
2066                         print_sockaddr(addr, sizeof(addr),
2067                                         &(*return_iplist)[i].ss);
2068                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
2069                                         name,
2070                                         name_type,
2071                                         addr,
2072                                         (*return_iplist)[i].port));
2073                 }
2074         }
2075
2076         namecache_store(name, name_type, *return_count, *return_iplist);
2077
2078         /* Display some debugging info */
2079
2080         if ( DEBUGLEVEL >= 10 ) {
2081                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
2082                                         *return_count));
2083
2084                 for (i = 0; i < *return_count; i++) {
2085                         char addr[INET6_ADDRSTRLEN];
2086                         print_sockaddr(addr, sizeof(addr),
2087                                         &(*return_iplist)[i].ss);
2088                         DEBUGADD(10, ("%s:%d ",
2089                                         addr,
2090                                         (*return_iplist)[i].port));
2091                 }
2092                 DEBUG(10, ("\n"));
2093         }
2094
2095         TALLOC_FREE(frame);
2096         return status;
2097 }
2098
2099 /********************************************************
2100  Internal interface to resolve a name into one IP address.
2101  Use this function if the string is either an IP address, DNS
2102  or host name or NetBIOS name. This uses the name switch in the
2103  smb.conf to determine the order of name resolution.
2104 *********************************************************/
2105
2106 bool resolve_name(const char *name,
2107                 struct sockaddr_storage *return_ss,
2108                 int name_type,
2109                 bool prefer_ipv4)
2110 {
2111         struct ip_service *ss_list = NULL;
2112         char *sitename = NULL;
2113         int count = 0;
2114
2115         if (is_ipaddress(name)) {
2116                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2117         }
2118
2119         sitename = sitename_fetch(lp_realm()); /* wild guess */
2120
2121         if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
2122                                                   &ss_list, &count,
2123                                                   lp_name_resolve_order()))) {
2124                 int i;
2125
2126                 if (prefer_ipv4) {
2127                         for (i=0; i<count; i++) {
2128                                 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2129                                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss) &&
2130                                                 (ss_list[i].ss.ss_family == AF_INET)) {
2131                                         *return_ss = ss_list[i].ss;
2132                                         SAFE_FREE(ss_list);
2133                                         SAFE_FREE(sitename);
2134                                         return True;
2135                                 }
2136                         }
2137                 }
2138
2139                 /* only return valid addresses for TCP connections */
2140                 for (i=0; i<count; i++) {
2141                         if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2142                                         !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2143                                 *return_ss = ss_list[i].ss;
2144                                 SAFE_FREE(ss_list);
2145                                 SAFE_FREE(sitename);
2146                                 return True;
2147                         }
2148                 }
2149         }
2150
2151         SAFE_FREE(ss_list);
2152         SAFE_FREE(sitename);
2153         return False;
2154 }
2155
2156 /********************************************************
2157  Internal interface to resolve a name into a list of IP addresses.
2158  Use this function if the string is either an IP address, DNS
2159  or host name or NetBIOS name. This uses the name switch in the
2160  smb.conf to determine the order of name resolution.
2161 *********************************************************/
2162
2163 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2164                 const char *name,
2165                 int name_type,
2166                 struct sockaddr_storage **return_ss_arr,
2167                 unsigned int *p_num_entries)
2168 {
2169         struct ip_service *ss_list = NULL;
2170         char *sitename = NULL;
2171         int count = 0;
2172         int i;
2173         unsigned int num_entries;
2174         NTSTATUS status;
2175
2176         *p_num_entries = 0;
2177         *return_ss_arr = NULL;
2178
2179         if (is_ipaddress(name)) {
2180                 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
2181                 if (!*return_ss_arr) {
2182                         return NT_STATUS_NO_MEMORY;
2183                 }
2184                 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2185                         TALLOC_FREE(*return_ss_arr);
2186                         return NT_STATUS_BAD_NETWORK_NAME;
2187                 }
2188                 *p_num_entries = 1;
2189                 return NT_STATUS_OK;
2190         }
2191
2192         sitename = sitename_fetch(lp_realm()); /* wild guess */
2193
2194         status = internal_resolve_name(name, name_type, sitename,
2195                                                   &ss_list, &count,
2196                                                   lp_name_resolve_order());
2197         SAFE_FREE(sitename);
2198
2199         if (!NT_STATUS_IS_OK(status)) {
2200                 return status;
2201         }
2202
2203         /* only return valid addresses for TCP connections */
2204         for (i=0, num_entries = 0; i<count; i++) {
2205                 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2206                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2207                         num_entries++;
2208                 }
2209         }
2210         if (num_entries == 0) {
2211                 SAFE_FREE(ss_list);
2212                 return NT_STATUS_BAD_NETWORK_NAME;
2213         }
2214
2215         *return_ss_arr = TALLOC_ARRAY(ctx,
2216                                 struct sockaddr_storage,
2217                                 num_entries);
2218         if (!(*return_ss_arr)) {
2219                 SAFE_FREE(ss_list);
2220                 return NT_STATUS_NO_MEMORY;
2221         }
2222
2223         for (i=0, num_entries = 0; i<count; i++) {
2224                 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2225                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2226                         (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2227                 }
2228         }
2229
2230         status = NT_STATUS_OK;
2231         *p_num_entries = num_entries;
2232
2233         SAFE_FREE(ss_list);
2234         return NT_STATUS_OK;
2235 }
2236
2237 /********************************************************
2238  Find the IP address of the master browser or DMB for a workgroup.
2239 *********************************************************/
2240
2241 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2242 {
2243         struct ip_service *ip_list = NULL;
2244         int count = 0;
2245         NTSTATUS status;
2246
2247         if (lp_disable_netbios()) {
2248                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
2249                 return false;
2250         }
2251
2252         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
2253                                        lp_name_resolve_order());
2254         if (NT_STATUS_IS_OK(status)) {
2255                 *master_ss = ip_list[0].ss;
2256                 SAFE_FREE(ip_list);
2257                 return true;
2258         }
2259
2260         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
2261                                        lp_name_resolve_order());
2262         if (NT_STATUS_IS_OK(status)) {
2263                 *master_ss = ip_list[0].ss;
2264                 SAFE_FREE(ip_list);
2265                 return true;
2266         }
2267
2268         SAFE_FREE(ip_list);
2269         return false;
2270 }
2271
2272 /********************************************************
2273  Get the IP address list of the primary domain controller
2274  for a domain.
2275 *********************************************************/
2276
2277 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
2278 {
2279         struct ip_service *ip_list = NULL;
2280         int count = 0;
2281         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2282
2283         /* Look up #1B name */
2284
2285         if (lp_security() == SEC_ADS) {
2286                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2287                                                &count, "ads");
2288         }
2289
2290         if (!NT_STATUS_IS_OK(status) || count == 0) {
2291                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2292                                                &count,
2293                                                lp_name_resolve_order());
2294                 if (!NT_STATUS_IS_OK(status)) {
2295                         return false;
2296                 }
2297         }
2298
2299         /* if we get more than 1 IP back we have to assume it is a
2300            multi-homed PDC and not a mess up */
2301
2302         if ( count > 1 ) {
2303                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
2304                 sort_service_list(ip_list, count);
2305         }
2306
2307         *pss = ip_list[0].ss;
2308         SAFE_FREE(ip_list);
2309         return true;
2310 }
2311
2312 /* Private enum type for lookups. */
2313
2314 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
2315
2316 /********************************************************
2317  Get the IP address list of the domain controllers for
2318  a domain.
2319 *********************************************************/
2320
2321 static NTSTATUS get_dc_list(const char *domain,
2322                         const char *sitename,
2323                         struct ip_service **ip_list,
2324                         int *count,
2325                         enum dc_lookup_type lookup_type,
2326                         bool *ordered)
2327 {
2328         char *resolve_order = NULL;
2329         char *saf_servername = NULL;
2330         char *pserver = NULL;
2331         const char *p;
2332         char *port_str = NULL;
2333         int port;
2334         char *name;
2335         int num_addresses = 0;
2336         int  local_count, i, j;
2337         struct ip_service *return_iplist = NULL;
2338         struct ip_service *auto_ip_list = NULL;
2339         bool done_auto_lookup = false;
2340         int auto_count = 0;
2341         NTSTATUS status;
2342         TALLOC_CTX *ctx = talloc_init("get_dc_list");
2343
2344         *ip_list = NULL;
2345         *count = 0;
2346
2347         if (!ctx) {
2348                 return NT_STATUS_NO_MEMORY;
2349         }
2350
2351         *ordered = False;
2352
2353         /* if we are restricted to solely using DNS for looking
2354            up a domain controller, make sure that host lookups
2355            are enabled for the 'name resolve order'.  If host lookups
2356            are disabled and ads_only is True, then set the string to
2357            NULL. */
2358
2359         resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
2360         if (!resolve_order) {
2361                 status = NT_STATUS_NO_MEMORY;
2362                 goto out;
2363         }
2364         strlower_m(resolve_order);
2365         if (lookup_type == DC_ADS_ONLY)  {
2366                 if (strstr( resolve_order, "host")) {
2367                         resolve_order = talloc_strdup(ctx, "ads");
2368
2369                         /* DNS SRV lookups used by the ads resolver
2370                            are already sorted by priority and weight */
2371                         *ordered = true;
2372                 } else {
2373                         resolve_order = talloc_strdup(ctx, "NULL");
2374                 }
2375         } else if (lookup_type == DC_KDC_ONLY) {
2376                 /* DNS SRV lookups used by the ads/kdc resolver
2377                    are already sorted by priority and weight */
2378                 *ordered = true;
2379                 resolve_order = talloc_strdup(ctx, "kdc");
2380         }
2381         if (!resolve_order) {
2382                 status = NT_STATUS_NO_MEMORY;
2383                 goto out;
2384         }
2385
2386         /* fetch the server we have affinity for.  Add the
2387            'password server' list to a search for our domain controllers */
2388
2389         saf_servername = saf_fetch( domain);
2390
2391         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
2392                 pserver = talloc_asprintf(ctx, "%s, %s",
2393                         saf_servername ? saf_servername : "",
2394                         lp_passwordserver());
2395         } else {
2396                 pserver = talloc_asprintf(ctx, "%s, *",
2397                         saf_servername ? saf_servername : "");
2398         }
2399
2400         SAFE_FREE(saf_servername);
2401         if (!pserver) {
2402                 status = NT_STATUS_NO_MEMORY;
2403                 goto out;
2404         }
2405
2406         /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
2407
2408         if (!*pserver ) {
2409                 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
2410                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2411                                              count, resolve_order);
2412                 goto out;
2413         }
2414
2415         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
2416
2417         /*
2418          * if '*' appears in the "password server" list then add
2419          * an auto lookup to the list of manually configured
2420          * DC's.  If any DC is listed by name, then the list should be
2421          * considered to be ordered
2422          */
2423
2424         p = pserver;
2425         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2426                 if (!done_auto_lookup && strequal(name, "*")) {
2427                         status = internal_resolve_name(domain, 0x1C, sitename,
2428                                                        &auto_ip_list,
2429                                                        &auto_count,
2430                                                        resolve_order);
2431                         if (NT_STATUS_IS_OK(status)) {
2432                                 num_addresses += auto_count;
2433                         }
2434                         done_auto_lookup = true;
2435                         DEBUG(8,("Adding %d DC's from auto lookup\n",
2436                                                 auto_count));
2437                 } else  {
2438                         num_addresses++;
2439                 }
2440         }
2441
2442         /* if we have no addresses and haven't done the auto lookup, then
2443            just return the list of DC's.  Or maybe we just failed. */
2444
2445         if ((num_addresses == 0)) {
2446                 if (done_auto_lookup) {
2447                         DEBUG(4,("get_dc_list: no servers found\n"));
2448                         status = NT_STATUS_NO_LOGON_SERVERS;
2449                         goto out;
2450                 }
2451                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2452                                              count, resolve_order);
2453                 goto out;
2454         }
2455
2456         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
2457                                         num_addresses)) == NULL) {
2458                 DEBUG(3,("get_dc_list: malloc fail !\n"));
2459                 status = NT_STATUS_NO_MEMORY;
2460                 goto out;
2461         }
2462
2463         p = pserver;
2464         local_count = 0;
2465
2466         /* fill in the return list now with real IP's */
2467
2468         while ((local_count<num_addresses) &&
2469                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2470                 struct sockaddr_storage name_ss;
2471
2472                 /* copy any addersses from the auto lookup */
2473
2474                 if (strequal(name, "*")) {
2475                         for (j=0; j<auto_count; j++) {
2476                                 char addr[INET6_ADDRSTRLEN];
2477                                 print_sockaddr(addr,
2478                                                 sizeof(addr),
2479                                                 &auto_ip_list[j].ss);
2480                                 /* Check for and don't copy any
2481                                  * known bad DC IP's. */
2482                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
2483                                                 domain,
2484                                                 addr))) {
2485                                         DEBUG(5,("get_dc_list: "
2486                                                 "negative entry %s removed "
2487                                                 "from DC list\n",
2488                                                 addr));
2489                                         continue;
2490                                 }
2491                                 return_iplist[local_count].ss =
2492                                         auto_ip_list[j].ss;
2493                                 return_iplist[local_count].port =
2494                                         auto_ip_list[j].port;
2495                                 local_count++;
2496                         }
2497                         continue;
2498                 }
2499
2500                 /* added support for address:port syntax for ads
2501                  * (not that I think anyone will ever run the LDAP
2502                  * server in an AD domain on something other than
2503                  * port 389 */
2504
2505                 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
2506                 if ((port_str=strchr(name, ':')) != NULL) {
2507                         *port_str = '\0';
2508                         port_str++;
2509                         port = atoi(port_str);
2510                 }
2511
2512                 /* explicit lookup; resolve_name() will
2513                  * handle names & IP addresses */
2514                 if (resolve_name( name, &name_ss, 0x20, true )) {
2515                         char addr[INET6_ADDRSTRLEN];
2516                         print_sockaddr(addr,
2517                                         sizeof(addr),
2518                                         &name_ss);
2519
2520                         /* Check for and don't copy any known bad DC IP's. */
2521                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2522                                                         addr)) ) {
2523                                 DEBUG(5,("get_dc_list: negative entry %s "
2524                                         "removed from DC list\n",
2525                                         name ));
2526                                 continue;
2527                         }
2528
2529                         return_iplist[local_count].ss = name_ss;
2530                         return_iplist[local_count].port = port;
2531                         local_count++;
2532                         *ordered = true;
2533                 }
2534         }
2535
2536         /* need to remove duplicates in the list if we have any
2537            explicit password servers */
2538
2539         if (local_count) {
2540                 local_count = remove_duplicate_addrs2(return_iplist,
2541                                 local_count );
2542         }
2543
2544         /* For DC's we always prioritize IPv4 due to W2K3 not
2545          * supporting LDAP, KRB5 or CLDAP over IPv6. */
2546
2547         if (local_count && return_iplist) {
2548                 prioritize_ipv4_list(return_iplist, local_count);
2549         }
2550
2551         if ( DEBUGLEVEL >= 4 ) {
2552                 DEBUG(4,("get_dc_list: returning %d ip addresses "
2553                                 "in an %sordered list\n",
2554                                 local_count,
2555                                 *ordered ? "":"un"));
2556                 DEBUG(4,("get_dc_list: "));
2557                 for ( i=0; i<local_count; i++ ) {
2558                         char addr[INET6_ADDRSTRLEN];
2559                         print_sockaddr(addr,
2560                                         sizeof(addr),
2561                                         &return_iplist[i].ss);
2562                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2563                 }
2564                 DEBUGADD(4,("\n"));
2565         }
2566
2567         *ip_list = return_iplist;
2568         *count = local_count;
2569
2570         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2571
2572   out:
2573
2574         if (!NT_STATUS_IS_OK(status)) {
2575                 SAFE_FREE(return_iplist);
2576                 *ip_list = NULL;
2577                 *count = 0;
2578         }
2579
2580         SAFE_FREE(auto_ip_list);
2581         TALLOC_FREE(ctx);
2582         return status;
2583 }
2584
2585 /*********************************************************************
2586  Small wrapper function to get the DC list and sort it if neccessary.
2587 *********************************************************************/
2588
2589 NTSTATUS get_sorted_dc_list( const char *domain,
2590                         const char *sitename,
2591                         struct ip_service **ip_list,
2592                         int *count,
2593                         bool ads_only )
2594 {
2595         bool ordered = false;
2596         NTSTATUS status;
2597         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2598
2599         *ip_list = NULL;
2600         *count = 0;
2601
2602         DEBUG(8,("get_sorted_dc_list: attempting lookup "
2603                 "for name %s (sitename %s) using [%s]\n",
2604                 domain,
2605                 sitename ? sitename : "NULL",
2606                 (ads_only ? "ads" : lp_name_resolve_order())));
2607
2608         if (ads_only) {
2609                 lookup_type = DC_ADS_ONLY;
2610         }
2611
2612         status = get_dc_list(domain, sitename, ip_list,
2613                         count, lookup_type, &ordered);
2614         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
2615             && sitename) {
2616                 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
2617                          " in site %s, fallback to all servers\n",
2618                          domain, sitename));
2619                 status = get_dc_list(domain, NULL, ip_list,
2620                                      count, lookup_type, &ordered);
2621         }
2622
2623         if (!NT_STATUS_IS_OK(status)) {
2624                 SAFE_FREE(*ip_list);
2625                 *count = 0;
2626                 return status;
2627         }
2628
2629         /* only sort if we don't already have an ordered list */
2630         if (!ordered) {
2631                 sort_service_list(*ip_list, *count);
2632         }
2633
2634         return NT_STATUS_OK;
2635 }
2636
2637 /*********************************************************************
2638  Get the KDC list - re-use all the logic in get_dc_list.
2639 *********************************************************************/
2640
2641 NTSTATUS get_kdc_list( const char *realm,
2642                         const char *sitename,
2643                         struct ip_service **ip_list,
2644                         int *count)
2645 {
2646         bool ordered;
2647         NTSTATUS status;
2648
2649         *count = 0;
2650         *ip_list = NULL;
2651
2652         status = get_dc_list(realm, sitename, ip_list,
2653                         count, DC_KDC_ONLY, &ordered);
2654
2655         if (!NT_STATUS_IS_OK(status)) {
2656                 SAFE_FREE(*ip_list);
2657                 *count = 0;
2658                 return status;
2659         }
2660
2661         /* only sort if we don't already have an ordered list */
2662         if ( !ordered ) {
2663                 sort_service_list(*ip_list, *count);
2664         }
2665
2666         return NT_STATUS_OK;
2667 }