s3: Add nb_trans_send/recv
[metze/samba/wip.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 NTSTATUS node_status_query(int fd,
694                            struct nmb_name *name,
695                            const struct sockaddr_storage *to_ss,
696                            TALLOC_CTX *mem_ctx,
697                            struct node_status **names,
698                            int *num_names,
699                            struct node_status_extra *extra)
700 {
701         bool found=False;
702         int retries = 2;
703         int retry_time = 2000;
704         struct timespec tp;
705         struct packet_struct p;
706         struct packet_struct *p2;
707         struct nmb_packet *nmb = &p.packet.nmb;
708         struct node_status *ret;
709
710         ZERO_STRUCT(p);
711
712         if (to_ss->ss_family != AF_INET) {
713                 /* Can't do node status to IPv6 */
714                 return NT_STATUS_INVALID_ADDRESS;
715         }
716         nmb->header.name_trn_id = generate_trn_id();
717         nmb->header.opcode = 0;
718         nmb->header.response = false;
719         nmb->header.nm_flags.bcast = false;
720         nmb->header.nm_flags.recursion_available = false;
721         nmb->header.nm_flags.recursion_desired = false;
722         nmb->header.nm_flags.trunc = false;
723         nmb->header.nm_flags.authoritative = false;
724         nmb->header.rcode = 0;
725         nmb->header.qdcount = 1;
726         nmb->header.ancount = 0;
727         nmb->header.nscount = 0;
728         nmb->header.arcount = 0;
729         nmb->question.question_name = *name;
730         nmb->question.question_type = 0x21;
731         nmb->question.question_class = 0x1;
732
733         p.ip = ((const struct sockaddr_in *)to_ss)->sin_addr;
734         p.port = NMB_PORT;
735         p.recv_fd = -1;
736         p.send_fd = fd;
737         p.timestamp = time(NULL);
738         p.packet_type = NMB_PACKET;
739
740         clock_gettime_mono(&tp);
741
742         if (!send_packet_request(&p))
743                 return NT_STATUS_NOT_FOUND;
744
745         retries--;
746
747         while (1) {
748                 struct timespec tp2;
749                 clock_gettime_mono(&tp2);
750                 if (nsec_time_diff(&tp2,&tp)/1000000 > retry_time) {
751                         if (!retries)
752                                 break;
753                         if (!found && !send_packet_request(&p))
754                                 return NT_STATUS_NOT_FOUND;
755                         clock_gettime_mono(&tp);
756                         retries--;
757                 }
758
759                 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
760                         struct nmb_packet *nmb2 = &p2->packet.nmb;
761                         debug_nmb_packet(p2);
762
763                         if (nmb2->header.opcode != 0 ||
764                             nmb2->header.nm_flags.bcast ||
765                             nmb2->header.rcode ||
766                             !nmb2->header.ancount ||
767                             nmb2->answers->rr_type != 0x21) {
768                                 /* XXXX what do we do with this? could be a
769                                    redirect, but we'll discard it for the
770                                    moment */
771                                 free_packet(p2);
772                                 continue;
773                         }
774
775                         ret = parse_node_status(
776                                 mem_ctx, &nmb2->answers->rdata[0], num_names,
777                                 extra);
778                         free_packet(p2);
779
780                         if (ret == NULL) {
781                                 return NT_STATUS_NO_MEMORY;
782                         }
783                         *names = ret;
784                         return NT_STATUS_OK;
785                 }
786         }
787
788         return NT_STATUS_IO_TIMEOUT;
789 }
790
791 /****************************************************************************
792  Find the first type XX name in a node status reply - used for finding
793  a servers name given its IP. Return the matched name in *name.
794 **************************************************************************/
795
796 bool name_status_find(const char *q_name,
797                         int q_type,
798                         int type,
799                         const struct sockaddr_storage *to_ss,
800                         fstring name)
801 {
802         char addr[INET6_ADDRSTRLEN];
803         struct sockaddr_storage ss;
804         struct node_status *addrs = NULL;
805         struct nmb_name nname;
806         int count, i;
807         int sock;
808         bool result = false;
809         NTSTATUS status;
810
811         if (lp_disable_netbios()) {
812                 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
813                                         q_name, q_type));
814                 return False;
815         }
816
817         print_sockaddr(addr, sizeof(addr), to_ss);
818
819         DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
820                    q_type, addr));
821
822         /* Check the cache first. */
823
824         if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
825                 return True;
826         }
827
828         if (to_ss->ss_family != AF_INET) {
829                 /* Can't do node status to IPv6 */
830                 return false;
831         }
832
833         if (!interpret_string_addr(&ss, lp_socket_address(),
834                                 AI_NUMERICHOST|AI_PASSIVE)) {
835                 zero_sockaddr(&ss);
836         }
837
838         sock = open_socket_in(SOCK_DGRAM, 0, 3, &ss, True);
839         if (sock == -1)
840                 goto done;
841
842         /* W2K PDC's seem not to respond to '*'#0. JRA */
843         make_nmb_name(&nname, q_name, q_type);
844         status = node_status_query(sock, &nname, to_ss, talloc_tos(),
845                                    &addrs, &count, NULL);
846         close(sock);
847         if (!NT_STATUS_IS_OK(status)) {
848                 goto done;
849         }
850
851         for (i=0;i<count;i++) {
852                 /* Find first one of the requested type that's not a GROUP. */
853                 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
854                         break;
855         }
856         if (i == count)
857                 goto done;
858
859         pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
860
861         /* Store the result in the cache. */
862         /* but don't store an entry for 0x1c names here.  Here we have
863            a single host and DOMAIN<0x1c> names should be a list of hosts */
864
865         if ( q_type != 0x1c ) {
866                 namecache_status_store(q_name, q_type, type, to_ss, name);
867         }
868
869         result = true;
870
871  done:
872         TALLOC_FREE(addrs);
873
874         DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
875
876         if (result)
877                 DEBUGADD(10, (", name %s ip address is %s", name, addr));
878
879         DEBUG(10, ("\n"));
880
881         return result;
882 }
883
884 /*
885   comparison function used by sort_addr_list
886 */
887
888 static int addr_compare(const struct sockaddr_storage *ss1,
889                         const struct sockaddr_storage *ss2)
890 {
891         int max_bits1=0, max_bits2=0;
892         int num_interfaces = iface_count();
893         int i;
894
895         /* Sort IPv4 addresses first. */
896         if (ss1->ss_family != ss2->ss_family) {
897                 if (ss2->ss_family == AF_INET) {
898                         return 1;
899                 } else {
900                         return -1;
901                 }
902         }
903
904         /* Here we know both addresses are of the same
905          * family. */
906
907         for (i=0;i<num_interfaces;i++) {
908                 const struct sockaddr_storage *pss = iface_n_bcast(i);
909                 unsigned char *p_ss1 = NULL;
910                 unsigned char *p_ss2 = NULL;
911                 unsigned char *p_if = NULL;
912                 size_t len = 0;
913                 int bits1, bits2;
914
915                 if (pss->ss_family != ss1->ss_family) {
916                         /* Ignore interfaces of the wrong type. */
917                         continue;
918                 }
919                 if (pss->ss_family == AF_INET) {
920                         p_if = (unsigned char *)
921                                 &((const struct sockaddr_in *)pss)->sin_addr;
922                         p_ss1 = (unsigned char *)
923                                 &((const struct sockaddr_in *)ss1)->sin_addr;
924                         p_ss2 = (unsigned char *)
925                                 &((const struct sockaddr_in *)ss2)->sin_addr;
926                         len = 4;
927                 }
928 #if defined(HAVE_IPV6)
929                 if (pss->ss_family == AF_INET6) {
930                         p_if = (unsigned char *)
931                                 &((const struct sockaddr_in6 *)pss)->sin6_addr;
932                         p_ss1 = (unsigned char *)
933                                 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
934                         p_ss2 = (unsigned char *)
935                                 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
936                         len = 16;
937                 }
938 #endif
939                 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
940                         continue;
941                 }
942                 bits1 = matching_len_bits(p_ss1, p_if, len);
943                 bits2 = matching_len_bits(p_ss2, p_if, len);
944                 max_bits1 = MAX(bits1, max_bits1);
945                 max_bits2 = MAX(bits2, max_bits2);
946         }
947
948         /* Bias towards directly reachable IPs */
949         if (iface_local((struct sockaddr *)ss1)) {
950                 if (ss1->ss_family == AF_INET) {
951                         max_bits1 += 32;
952                 } else {
953                         max_bits1 += 128;
954                 }
955         }
956         if (iface_local((struct sockaddr *)ss2)) {
957                 if (ss2->ss_family == AF_INET) {
958                         max_bits2 += 32;
959                 } else {
960                         max_bits2 += 128;
961                 }
962         }
963         return max_bits2 - max_bits1;
964 }
965
966 /*******************************************************************
967  compare 2 ldap IPs by nearness to our interfaces - used in qsort
968 *******************************************************************/
969
970 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
971 {
972         int result;
973
974         if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
975                 return result;
976         }
977
978         if (ss1->port > ss2->port) {
979                 return 1;
980         }
981
982         if (ss1->port < ss2->port) {
983                 return -1;
984         }
985
986         return 0;
987 }
988
989 /*
990   sort an IP list so that names that are close to one of our interfaces
991   are at the top. This prevents the problem where a WINS server returns an IP
992   that is not reachable from our subnet as the first match
993 */
994
995 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
996 {
997         if (count <= 1) {
998                 return;
999         }
1000
1001         TYPESAFE_QSORT(sslist, count, addr_compare);
1002 }
1003
1004 static void sort_service_list(struct ip_service *servlist, int count)
1005 {
1006         if (count <= 1) {
1007                 return;
1008         }
1009
1010         TYPESAFE_QSORT(servlist, count, ip_service_compare);
1011 }
1012
1013 /**********************************************************************
1014  Remove any duplicate address/port pairs in the list
1015  *********************************************************************/
1016
1017 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
1018 {
1019         int i, j;
1020
1021         DEBUG(10,("remove_duplicate_addrs2: "
1022                         "looking for duplicate address/port pairs\n"));
1023
1024         /* one loop to remove duplicates */
1025         for ( i=0; i<count; i++ ) {
1026                 if ( is_zero_addr((struct sockaddr *)&iplist[i].ss)) {
1027                         continue;
1028                 }
1029
1030                 for ( j=i+1; j<count; j++ ) {
1031                         if (sockaddr_equal((struct sockaddr *)&iplist[i].ss, (struct sockaddr *)&iplist[j].ss) &&
1032                                         iplist[i].port == iplist[j].port) {
1033                                 zero_sockaddr(&iplist[j].ss);
1034                         }
1035                 }
1036         }
1037
1038         /* one loop to clean up any holes we left */
1039         /* first ip should never be a zero_ip() */
1040         for (i = 0; i<count; ) {
1041                 if (is_zero_addr((struct sockaddr *)&iplist[i].ss) ) {
1042                         if (i != count-1) {
1043                                 memmove(&iplist[i], &iplist[i+1],
1044                                         (count - i - 1)*sizeof(iplist[i]));
1045                         }
1046                         count--;
1047                         continue;
1048                 }
1049                 i++;
1050         }
1051
1052         return count;
1053 }
1054
1055 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1056 {
1057         TALLOC_CTX *frame = talloc_stackframe();
1058         struct ip_service *iplist_new = TALLOC_ARRAY(frame, struct ip_service, count);
1059         int i, j;
1060
1061         if (iplist_new == NULL) {
1062                 TALLOC_FREE(frame);
1063                 return false;
1064         }
1065
1066         j = 0;
1067
1068         /* Copy IPv4 first. */
1069         for (i = 0; i < count; i++) {
1070                 if (iplist[i].ss.ss_family == AF_INET) {
1071                         iplist_new[j++] = iplist[i];
1072                 }
1073         }
1074
1075         /* Copy IPv6. */
1076         for (i = 0; i < count; i++) {
1077                 if (iplist[i].ss.ss_family != AF_INET) {
1078                         iplist_new[j++] = iplist[i];
1079                 }
1080         }
1081
1082         memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1083         TALLOC_FREE(frame);
1084         return true;
1085 }
1086
1087 /****************************************************************************
1088  Do a netbios name query to find someones IP.
1089  Returns an array of IP addresses or NULL if none.
1090  *count will be set to the number of addresses returned.
1091  *timed_out is set if we failed by timing out
1092 ****************************************************************************/
1093
1094 NTSTATUS name_query(int fd,
1095                         const char *name,
1096                         int name_type,
1097                         bool bcast,
1098                         bool recurse,
1099                         const struct sockaddr_storage *to_ss,
1100                         TALLOC_CTX *mem_ctx,
1101                         struct sockaddr_storage **addrs,
1102                         int *count,
1103                         int *flags,
1104                         bool *timed_out)
1105 {
1106         bool found=false;
1107         int i, retries = 3;
1108         int retry_time = bcast?250:2000;
1109         struct timespec tp;
1110         struct packet_struct p;
1111         struct packet_struct *p2;
1112         struct nmb_packet *nmb = &p.packet.nmb;
1113         struct sockaddr_storage *ss_list = NULL;
1114
1115         if (lp_disable_netbios()) {
1116                 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1117                                         name, name_type));
1118                 return NT_STATUS_NOT_FOUND;
1119         }
1120
1121         if (to_ss->ss_family != AF_INET) {
1122                 return NT_STATUS_INVALID_ADDRESS;
1123         }
1124
1125         if (timed_out) {
1126                 *timed_out = false;
1127         }
1128
1129         memset((char *)&p,'\0',sizeof(p));
1130         (*count) = 0;
1131         (*flags) = 0;
1132
1133         nmb->header.name_trn_id = generate_trn_id();
1134         nmb->header.opcode = 0;
1135         nmb->header.response = false;
1136         nmb->header.nm_flags.bcast = bcast;
1137         nmb->header.nm_flags.recursion_available = false;
1138         nmb->header.nm_flags.recursion_desired = recurse;
1139         nmb->header.nm_flags.trunc = false;
1140         nmb->header.nm_flags.authoritative = false;
1141         nmb->header.rcode = 0;
1142         nmb->header.qdcount = 1;
1143         nmb->header.ancount = 0;
1144         nmb->header.nscount = 0;
1145         nmb->header.arcount = 0;
1146
1147         make_nmb_name(&nmb->question.question_name,name,name_type);
1148
1149         nmb->question.question_type = 0x20;
1150         nmb->question.question_class = 0x1;
1151
1152         p.ip = ((struct sockaddr_in *)to_ss)->sin_addr;
1153         p.port = NMB_PORT;
1154         p.recv_fd = -1;
1155         p.send_fd = fd;
1156         p.timestamp = time(NULL);
1157         p.packet_type = NMB_PACKET;
1158
1159         clock_gettime_mono(&tp);
1160
1161         if (!send_packet_request(&p))
1162                 return NT_STATUS_NOT_FOUND;
1163
1164         retries--;
1165
1166         while (1) {
1167                 struct timespec tp2;
1168
1169                 clock_gettime_mono(&tp2);
1170                 if (nsec_time_diff(&tp2,&tp)/1000000 > retry_time) {
1171                         if (!retries)
1172                                 break;
1173                         if (!found && !send_packet_request(&p))
1174                                 return NT_STATUS_NOT_FOUND;
1175                         clock_gettime_mono(&tp);
1176                         retries--;
1177                 }
1178                 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
1179                         struct nmb_packet *nmb2 = &p2->packet.nmb;
1180                         debug_nmb_packet(p2);
1181
1182                         /* If we get a Negative Name Query Response from a WINS
1183                          * server, we should report it and give up.
1184                          */
1185                         if( 0 == nmb2->header.opcode    /* A query response   */
1186                             && !(bcast)                 /* from a WINS server */
1187                             && nmb2->header.rcode       /* Error returned     */
1188                                 ) {
1189
1190                                 if( DEBUGLVL( 3 ) ) {
1191                                         /* Only executed if DEBUGLEVEL >= 3 */
1192                                         dbgtext( "Negative name query "
1193                                                 "response, rcode 0x%02x: ",
1194                                                 nmb2->header.rcode );
1195                                         switch( nmb2->header.rcode ) {
1196                                         case 0x01:
1197                                                 dbgtext( "Request "
1198                                                 "was invalidly formatted.\n" );
1199                                                 break;
1200                                         case 0x02:
1201                                                 dbgtext( "Problem with NBNS, "
1202                                                 "cannot process name.\n");
1203                                                 break;
1204                                         case 0x03:
1205                                                 dbgtext( "The name requested "
1206                                                 "does not exist.\n" );
1207                                                 break;
1208                                         case 0x04:
1209                                                 dbgtext( "Unsupported request "
1210                                                 "error.\n" );
1211                                                 break;
1212                                         case 0x05:
1213                                                 dbgtext( "Query refused "
1214                                                 "error.\n" );
1215                                                 break;
1216                                         default:
1217                                                 dbgtext( "Unrecognized error "
1218                                                 "code.\n" );
1219                                                 break;
1220                                         }
1221                                 }
1222                                 free_packet(p2);
1223                                 return NT_STATUS_NOT_FOUND;
1224                         }
1225
1226                         if (nmb2->header.opcode != 0 ||
1227                             nmb2->header.nm_flags.bcast ||
1228                             nmb2->header.rcode ||
1229                             !nmb2->header.ancount) {
1230                                 /*
1231                                  * XXXX what do we do with this? Could be a
1232                                  * redirect, but we'll discard it for the
1233                                  * moment.
1234                                  */
1235                                 free_packet(p2);
1236                                 continue;
1237                         }
1238
1239                         ss_list = TALLOC_REALLOC_ARRAY(mem_ctx, ss_list,
1240                                                 struct sockaddr_storage,
1241                                                 (*count) +
1242                                                 nmb2->answers->rdlength/6);
1243
1244                         if (!ss_list) {
1245                                 DEBUG(0,("name_query: Realloc failed.\n"));
1246                                 free_packet(p2);
1247                                 return NT_STATUS_NO_MEMORY;
1248                         }
1249
1250                         DEBUG(2,("Got a positive name query response "
1251                                         "from %s ( ",
1252                                         inet_ntoa(p2->ip)));
1253
1254                         for (i=0;i<nmb2->answers->rdlength/6;i++) {
1255                                 struct in_addr ip;
1256                                 putip((char *)&ip,&nmb2->answers->rdata[2+i*6]);
1257                                 in_addr_to_sockaddr_storage(&ss_list[(*count)],
1258                                                 ip);
1259                                 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1260                                 (*count)++;
1261                         }
1262                         DEBUGADD(2,(")\n"));
1263
1264                         found=true;
1265                         retries=0;
1266                         /* We add the flags back ... */
1267                         if (nmb2->header.response)
1268                                 (*flags) |= NM_FLAGS_RS;
1269                         if (nmb2->header.nm_flags.authoritative)
1270                                 (*flags) |= NM_FLAGS_AA;
1271                         if (nmb2->header.nm_flags.trunc)
1272                                 (*flags) |= NM_FLAGS_TC;
1273                         if (nmb2->header.nm_flags.recursion_desired)
1274                                 (*flags) |= NM_FLAGS_RD;
1275                         if (nmb2->header.nm_flags.recursion_available)
1276                                 (*flags) |= NM_FLAGS_RA;
1277                         if (nmb2->header.nm_flags.bcast)
1278                                 (*flags) |= NM_FLAGS_B;
1279                         free_packet(p2);
1280                         /*
1281                          * If we're doing a unicast lookup we only
1282                          * expect one reply. Don't wait the full 2
1283                          * seconds if we got one. JRA.
1284                          */
1285                         if(!bcast && found)
1286                                 break;
1287                 }
1288         }
1289
1290         /* only set timed_out if we didn't fund what we where looking for*/
1291
1292         if ( !found && timed_out ) {
1293                 *timed_out = true;
1294         }
1295
1296         /* sort the ip list so we choose close servers first if possible */
1297         sort_addr_list(ss_list, *count);
1298
1299         *addrs = ss_list;
1300         return NT_STATUS_OK;
1301 }
1302
1303 /********************************************************
1304  convert an array if struct sockaddr_storage to struct ip_service
1305  return false on failure.  Port is set to PORT_NONE;
1306 *********************************************************/
1307
1308 static bool convert_ss2service(struct ip_service **return_iplist,
1309                 const struct sockaddr_storage *ss_list,
1310                 int count)
1311 {
1312         int i;
1313
1314         if ( count==0 || !ss_list )
1315                 return False;
1316
1317         /* copy the ip address; port will be PORT_NONE */
1318         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
1319                         NULL) {
1320                 DEBUG(0,("convert_ip2service: malloc failed "
1321                         "for %d enetries!\n", count ));
1322                 return False;
1323         }
1324
1325         for ( i=0; i<count; i++ ) {
1326                 (*return_iplist)[i].ss   = ss_list[i];
1327                 (*return_iplist)[i].port = PORT_NONE;
1328         }
1329
1330         return true;
1331 }
1332
1333 /********************************************************
1334  Resolve via "bcast" method.
1335 *********************************************************/
1336
1337 NTSTATUS name_resolve_bcast(const char *name,
1338                         int name_type,
1339                         struct ip_service **return_iplist,
1340                         int *return_count)
1341 {
1342         int sock, i;
1343         int num_interfaces = iface_count();
1344         struct sockaddr_storage *ss_list;
1345         struct sockaddr_storage ss;
1346         NTSTATUS status = NT_STATUS_NOT_FOUND;
1347
1348         if (lp_disable_netbios()) {
1349                 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1350                                         name, name_type));
1351                 return NT_STATUS_INVALID_PARAMETER;
1352         }
1353
1354         *return_iplist = NULL;
1355         *return_count = 0;
1356
1357         /*
1358          * "bcast" means do a broadcast lookup on all the local interfaces.
1359          */
1360
1361         DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
1362                 "for name %s<0x%x>\n", name, name_type));
1363
1364         if (!interpret_string_addr(&ss, lp_socket_address(),
1365                                 AI_NUMERICHOST|AI_PASSIVE)) {
1366                 zero_sockaddr(&ss);
1367         }
1368
1369         sock = open_socket_in( SOCK_DGRAM, 0, 3, &ss, true );
1370         if (sock == -1) {
1371                 return map_nt_error_from_unix(errno);
1372         }
1373
1374         set_socket_options(sock,"SO_BROADCAST");
1375         /*
1376          * Lookup the name on all the interfaces, return on
1377          * the first successful match.
1378          */
1379         for( i = num_interfaces-1; i >= 0; i--) {
1380                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1381                 int flags;
1382
1383                 /* Done this way to fix compiler error on IRIX 5.x */
1384                 if (!pss) {
1385                         continue;
1386                 }
1387                 status = name_query(sock, name, name_type, true, true, pss,
1388                                     talloc_tos(), &ss_list, return_count,
1389                                     &flags, NULL);
1390                 if (NT_STATUS_IS_OK(status)) {
1391                         goto success;
1392                 }
1393         }
1394
1395         /* failed - no response */
1396
1397         close(sock);
1398         return status;
1399
1400 success:
1401
1402         if (!convert_ss2service(return_iplist, ss_list, *return_count) )
1403                 status = NT_STATUS_NO_MEMORY;
1404
1405         TALLOC_FREE(ss_list);
1406         close(sock);
1407         return status;
1408 }
1409
1410 /********************************************************
1411  Resolve via "wins" method.
1412 *********************************************************/
1413
1414 NTSTATUS resolve_wins(const char *name,
1415                 int name_type,
1416                 struct ip_service **return_iplist,
1417                 int *return_count)
1418 {
1419         int sock, t, i;
1420         char **wins_tags;
1421         struct sockaddr_storage src_ss, *ss_list = NULL;
1422         struct in_addr src_ip;
1423         NTSTATUS status;
1424
1425         if (lp_disable_netbios()) {
1426                 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1427                                         name, name_type));
1428                 return NT_STATUS_INVALID_PARAMETER;
1429         }
1430
1431         *return_iplist = NULL;
1432         *return_count = 0;
1433
1434         DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1435                                 name, name_type));
1436
1437         if (wins_srv_count() < 1) {
1438                 DEBUG(3,("resolve_wins: WINS server resolution selected "
1439                         "and no WINS servers listed.\n"));
1440                 return NT_STATUS_INVALID_PARAMETER;
1441         }
1442
1443         /* we try a lookup on each of the WINS tags in turn */
1444         wins_tags = wins_srv_tags();
1445
1446         if (!wins_tags) {
1447                 /* huh? no tags?? give up in disgust */
1448                 return NT_STATUS_INVALID_PARAMETER;
1449         }
1450
1451         /* the address we will be sending from */
1452         if (!interpret_string_addr(&src_ss, lp_socket_address(),
1453                                 AI_NUMERICHOST|AI_PASSIVE)) {
1454                 zero_sockaddr(&src_ss);
1455         }
1456
1457         if (src_ss.ss_family != AF_INET) {
1458                 char addr[INET6_ADDRSTRLEN];
1459                 print_sockaddr(addr, sizeof(addr), &src_ss);
1460                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1461                         "on IPv6 address %s\n",
1462                         addr));
1463                 wins_srv_tags_free(wins_tags);
1464                 return NT_STATUS_INVALID_PARAMETER;
1465         }
1466
1467         src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1468
1469         /* in the worst case we will try every wins server with every
1470            tag! */
1471         for (t=0; wins_tags && wins_tags[t]; t++) {
1472                 int srv_count = wins_srv_count_tag(wins_tags[t]);
1473                 for (i=0; i<srv_count; i++) {
1474                         struct sockaddr_storage wins_ss;
1475                         struct in_addr wins_ip;
1476                         int flags;
1477                         bool timed_out;
1478
1479                         wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1480
1481                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
1482                                 /* yikes! we'll loop forever */
1483                                 continue;
1484                         }
1485
1486                         /* skip any that have been unresponsive lately */
1487                         if (wins_srv_is_dead(wins_ip, src_ip)) {
1488                                 continue;
1489                         }
1490
1491                         DEBUG(3,("resolve_wins: using WINS server %s "
1492                                 "and tag '%s'\n",
1493                                 inet_ntoa(wins_ip), wins_tags[t]));
1494
1495                         sock = open_socket_in(SOCK_DGRAM, 0, 3, &src_ss, true);
1496                         if (sock == -1) {
1497                                 continue;
1498                         }
1499
1500                         in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1501                         status = name_query(sock,
1502                                                 name,
1503                                                 name_type,
1504                                                 false,
1505                                                 true,
1506                                                 &wins_ss,
1507                                                 talloc_tos(),
1508                                                 &ss_list,
1509                                                 return_count,
1510                                                 &flags,
1511                                                 &timed_out);
1512
1513                         /* exit loop if we got a list of addresses */
1514
1515                         if (NT_STATUS_IS_OK(status)) {
1516                                 goto success;
1517                         }
1518
1519                         close(sock);
1520
1521                         if (timed_out) {
1522                                 /* Timed out waiting for WINS server to
1523                                  * respond.
1524                                  * Mark it dead. */
1525                                 wins_srv_died(wins_ip, src_ip);
1526                         } else {
1527                                 /* The name definitely isn't in this
1528                                    group of WINS servers.
1529                                    goto the next group  */
1530                                 break;
1531                         }
1532                 }
1533         }
1534
1535         wins_srv_tags_free(wins_tags);
1536         return NT_STATUS_NO_LOGON_SERVERS;
1537
1538 success:
1539
1540         status = NT_STATUS_OK;
1541         if (!convert_ss2service(return_iplist, ss_list, *return_count))
1542                 status = NT_STATUS_INVALID_PARAMETER;
1543
1544         TALLOC_FREE(ss_list);
1545         wins_srv_tags_free(wins_tags);
1546         close(sock);
1547
1548         return status;
1549 }
1550
1551 /********************************************************
1552  Resolve via "lmhosts" method.
1553 *********************************************************/
1554
1555 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1556                                 struct ip_service **return_iplist,
1557                                 int *return_count)
1558 {
1559         /*
1560          * "lmhosts" means parse the local lmhosts file.
1561          */
1562         struct sockaddr_storage *ss_list;
1563         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1564         TALLOC_CTX *ctx = NULL;
1565
1566         *return_iplist = NULL;
1567         *return_count = 0;
1568
1569         DEBUG(3,("resolve_lmhosts: "
1570                 "Attempting lmhosts lookup for name %s<0x%x>\n",
1571                 name, name_type));
1572
1573         ctx = talloc_init("resolve_lmhosts");
1574         if (!ctx) {
1575                 return NT_STATUS_NO_MEMORY;
1576         }
1577
1578         status = resolve_lmhosts_file_as_sockaddr(get_dyn_LMHOSTSFILE(), 
1579                                                   name, name_type, 
1580                                                   ctx, 
1581                                                   &ss_list, 
1582                                                   return_count);
1583         if (NT_STATUS_IS_OK(status)) {
1584                 if (convert_ss2service(return_iplist, 
1585                                        ss_list,
1586                                        *return_count)) {
1587                         talloc_free(ctx);
1588                         return NT_STATUS_OK;
1589                 } else {
1590                         talloc_free(ctx);
1591                         return NT_STATUS_NO_MEMORY;
1592                 }
1593         }
1594         talloc_free(ctx);
1595         return status;
1596 }
1597
1598
1599 /********************************************************
1600  Resolve via "hosts" method.
1601 *********************************************************/
1602
1603 static NTSTATUS resolve_hosts(const char *name, int name_type,
1604                               struct ip_service **return_iplist,
1605                               int *return_count)
1606 {
1607         /*
1608          * "host" means do a localhost, or dns lookup.
1609          */
1610         struct addrinfo hints;
1611         struct addrinfo *ailist = NULL;
1612         struct addrinfo *res = NULL;
1613         int ret = -1;
1614         int i = 0;
1615
1616         if ( name_type != 0x20 && name_type != 0x0) {
1617                 DEBUG(5, ("resolve_hosts: not appropriate "
1618                         "for name type <0x%x>\n",
1619                         name_type));
1620                 return NT_STATUS_INVALID_PARAMETER;
1621         }
1622
1623         *return_iplist = NULL;
1624         *return_count = 0;
1625
1626         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1627                                 name, name_type));
1628
1629         ZERO_STRUCT(hints);
1630         /* By default make sure it supports TCP. */
1631         hints.ai_socktype = SOCK_STREAM;
1632         hints.ai_flags = AI_ADDRCONFIG;
1633
1634 #if !defined(HAVE_IPV6)
1635         /* Unless we have IPv6, we really only want IPv4 addresses back. */
1636         hints.ai_family = AF_INET;
1637 #endif
1638
1639         ret = getaddrinfo(name,
1640                         NULL,
1641                         &hints,
1642                         &ailist);
1643         if (ret) {
1644                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1645                         name,
1646                         gai_strerror(ret) ));
1647         }
1648
1649         for (res = ailist; res; res = res->ai_next) {
1650                 struct sockaddr_storage ss;
1651
1652                 if (!res->ai_addr || res->ai_addrlen == 0) {
1653                         continue;
1654                 }
1655
1656                 ZERO_STRUCT(ss);
1657                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1658
1659                 *return_count += 1;
1660
1661                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1662                                                 struct ip_service,
1663                                                 *return_count);
1664                 if (!*return_iplist) {
1665                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
1666                         freeaddrinfo(ailist);
1667                         return NT_STATUS_NO_MEMORY;
1668                 }
1669                 (*return_iplist)[i].ss = ss;
1670                 (*return_iplist)[i].port = PORT_NONE;
1671                 i++;
1672         }
1673         if (ailist) {
1674                 freeaddrinfo(ailist);
1675         }
1676         if (*return_count) {
1677                 return NT_STATUS_OK;
1678         }
1679         return NT_STATUS_UNSUCCESSFUL;
1680 }
1681
1682 /********************************************************
1683  Resolve via "ADS" method.
1684 *********************************************************/
1685
1686 static NTSTATUS resolve_ads(const char *name,
1687                             int name_type,
1688                             const char *sitename,
1689                             struct ip_service **return_iplist,
1690                             int *return_count)
1691 {
1692         int                     i, j;
1693         NTSTATUS                status;
1694         TALLOC_CTX              *ctx;
1695         struct dns_rr_srv       *dcs = NULL;
1696         int                     numdcs = 0;
1697         int                     numaddrs = 0;
1698
1699         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1700             (name_type != 0x1b)) {
1701                 return NT_STATUS_INVALID_PARAMETER;
1702         }
1703
1704         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1705                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1706                 return NT_STATUS_NO_MEMORY;
1707         }
1708
1709         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1710
1711         switch (name_type) {
1712                 case 0x1b:
1713                         DEBUG(5,("resolve_ads: Attempting to resolve "
1714                                  "PDC for %s using DNS\n", name));
1715                         status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1716                         break;
1717
1718                 case 0x1c:
1719                         DEBUG(5,("resolve_ads: Attempting to resolve "
1720                                  "DCs for %s using DNS\n", name));
1721                         status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1722                                                    &numdcs);
1723                         break;
1724                 case KDC_NAME_TYPE:
1725                         DEBUG(5,("resolve_ads: Attempting to resolve "
1726                                  "KDCs for %s using DNS\n", name));
1727                         status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1728                                                     &numdcs);
1729                         break;
1730                 default:
1731                         status = NT_STATUS_INVALID_PARAMETER;
1732                         break;
1733         }
1734
1735         if ( !NT_STATUS_IS_OK( status ) ) {
1736                 talloc_destroy(ctx);
1737                 return status;
1738         }
1739
1740         for (i=0;i<numdcs;i++) {
1741                 numaddrs += MAX(dcs[i].num_ips,1);
1742         }
1743
1744         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1745                         NULL ) {
1746                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1747                                         numaddrs ));
1748                 talloc_destroy(ctx);
1749                 return NT_STATUS_NO_MEMORY;
1750         }
1751
1752         /* now unroll the list of IP addresses */
1753
1754         *return_count = 0;
1755         i = 0;
1756         j = 0;
1757         while ( i < numdcs && (*return_count<numaddrs) ) {
1758                 struct ip_service *r = &(*return_iplist)[*return_count];
1759
1760                 r->port = dcs[i].port;
1761
1762                 /* If we don't have an IP list for a name, lookup it up */
1763
1764                 if (!dcs[i].ss_s) {
1765                         interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1766                         i++;
1767                         j = 0;
1768                 } else {
1769                         /* use the IP addresses from the SRV sresponse */
1770
1771                         if ( j >= dcs[i].num_ips ) {
1772                                 i++;
1773                                 j = 0;
1774                                 continue;
1775                         }
1776
1777                         r->ss = dcs[i].ss_s[j];
1778                         j++;
1779                 }
1780
1781                 /* make sure it is a valid IP.  I considered checking the
1782                  * negative connection cache, but this is the wrong place
1783                  * for it. Maybe only as a hack. After think about it, if
1784                  * all of the IP addresses returned from DNS are dead, what
1785                  * hope does a netbios name lookup have ? The standard reason
1786                  * for falling back to netbios lookups is that our DNS server
1787                  * doesn't know anything about the DC's   -- jerry */
1788
1789                 if (!is_zero_addr((struct sockaddr *)&r->ss)) {
1790                         (*return_count)++;
1791                 }
1792         }
1793
1794         talloc_destroy(ctx);
1795         return NT_STATUS_OK;
1796 }
1797
1798 /*******************************************************************
1799  Internal interface to resolve a name into an IP address.
1800  Use this function if the string is either an IP address, DNS
1801  or host name or NetBIOS name. This uses the name switch in the
1802  smb.conf to determine the order of name resolution.
1803
1804  Added support for ip addr/port to support ADS ldap servers.
1805  the only place we currently care about the port is in the
1806  resolve_hosts() when looking up DC's via SRV RR entries in DNS
1807 **********************************************************************/
1808
1809 NTSTATUS internal_resolve_name(const char *name,
1810                                 int name_type,
1811                                 const char *sitename,
1812                                 struct ip_service **return_iplist,
1813                                 int *return_count,
1814                                 const char *resolve_order)
1815 {
1816         char *tok;
1817         const char *ptr;
1818         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1819         int i;
1820         TALLOC_CTX *frame = NULL;
1821
1822         *return_iplist = NULL;
1823         *return_count = 0;
1824
1825         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1826                         name, name_type, sitename ? sitename : "(null)"));
1827
1828         if (is_ipaddress(name)) {
1829                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1830                                 NULL) {
1831                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1832                         return NT_STATUS_NO_MEMORY;
1833                 }
1834
1835                 /* ignore the port here */
1836                 (*return_iplist)->port = PORT_NONE;
1837
1838                 /* if it's in the form of an IP address then get the lib to interpret it */
1839                 if (!interpret_string_addr(&(*return_iplist)->ss,
1840                                         name, AI_NUMERICHOST)) {
1841                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
1842                                 "failed on %s\n",
1843                                 name));
1844                         SAFE_FREE(*return_iplist);
1845                         return NT_STATUS_INVALID_PARAMETER;
1846                 }
1847                 *return_count = 1;
1848                 return NT_STATUS_OK;
1849         }
1850
1851         /* Check name cache */
1852
1853         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1854                 /* This could be a negative response */
1855                 if (*return_count > 0) {
1856                         return NT_STATUS_OK;
1857                 } else {
1858                         return NT_STATUS_UNSUCCESSFUL;
1859                 }
1860         }
1861
1862         /* set the name resolution order */
1863
1864         if (strcmp( resolve_order, "NULL") == 0) {
1865                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1866                 return NT_STATUS_INVALID_PARAMETER;
1867         }
1868
1869         if (!resolve_order[0]) {
1870                 ptr = "host";
1871         } else {
1872                 ptr = resolve_order;
1873         }
1874
1875         /* iterate through the name resolution backends */
1876
1877         frame = talloc_stackframe();
1878         while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
1879                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1880                         status = resolve_hosts(name, name_type, return_iplist,
1881                                                return_count);
1882                         if (NT_STATUS_IS_OK(status)) {
1883                                 goto done;
1884                         }
1885                 } else if(strequal( tok, "kdc")) {
1886                         /* deal with KDC_NAME_TYPE names here.
1887                          * This will result in a SRV record lookup */
1888                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1889                                              return_iplist, return_count);
1890                         if (NT_STATUS_IS_OK(status)) {
1891                                 /* Ensure we don't namecache
1892                                  * this with the KDC port. */
1893                                 name_type = KDC_NAME_TYPE;
1894                                 goto done;
1895                         }
1896                 } else if(strequal( tok, "ads")) {
1897                         /* deal with 0x1c and 0x1b names here.
1898                          * This will result in a SRV record lookup */
1899                         status = resolve_ads(name, name_type, sitename,
1900                                              return_iplist, return_count);
1901                         if (NT_STATUS_IS_OK(status)) {
1902                                 goto done;
1903                         }
1904                 } else if(strequal( tok, "lmhosts")) {
1905                         status = resolve_lmhosts(name, name_type,
1906                                                  return_iplist, return_count);
1907                         if (NT_STATUS_IS_OK(status)) {
1908                                 goto done;
1909                         }
1910                 } else if(strequal( tok, "wins")) {
1911                         /* don't resolve 1D via WINS */
1912                         if (name_type != 0x1D) {
1913                                 status = resolve_wins(name, name_type,
1914                                                       return_iplist,
1915                                                       return_count);
1916                                 if (NT_STATUS_IS_OK(status)) {
1917                                         goto done;
1918                                 }
1919                         }
1920                 } else if(strequal( tok, "bcast")) {
1921                         status = name_resolve_bcast(name, name_type,
1922                                                     return_iplist,
1923                                                     return_count);
1924                         if (NT_STATUS_IS_OK(status)) {
1925                                 goto done;
1926                         }
1927                 } else {
1928                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
1929                                 tok));
1930                 }
1931         }
1932
1933         /* All of the resolve_* functions above have returned false. */
1934
1935         TALLOC_FREE(frame);
1936         SAFE_FREE(*return_iplist);
1937         *return_count = 0;
1938
1939         return NT_STATUS_UNSUCCESSFUL;
1940
1941   done:
1942
1943         /* Remove duplicate entries.  Some queries, notably #1c (domain
1944         controllers) return the PDC in iplist[0] and then all domain
1945         controllers including the PDC in iplist[1..n].  Iterating over
1946         the iplist when the PDC is down will cause two sets of timeouts. */
1947
1948         if ( *return_count ) {
1949                 *return_count = remove_duplicate_addrs2(*return_iplist,
1950                                         *return_count );
1951         }
1952
1953         /* Save in name cache */
1954         if ( DEBUGLEVEL >= 100 ) {
1955                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
1956                         char addr[INET6_ADDRSTRLEN];
1957                         print_sockaddr(addr, sizeof(addr),
1958                                         &(*return_iplist)[i].ss);
1959                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
1960                                         name,
1961                                         name_type,
1962                                         addr,
1963                                         (*return_iplist)[i].port));
1964                 }
1965         }
1966
1967         namecache_store(name, name_type, *return_count, *return_iplist);
1968
1969         /* Display some debugging info */
1970
1971         if ( DEBUGLEVEL >= 10 ) {
1972                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
1973                                         *return_count));
1974
1975                 for (i = 0; i < *return_count; i++) {
1976                         char addr[INET6_ADDRSTRLEN];
1977                         print_sockaddr(addr, sizeof(addr),
1978                                         &(*return_iplist)[i].ss);
1979                         DEBUGADD(10, ("%s:%d ",
1980                                         addr,
1981                                         (*return_iplist)[i].port));
1982                 }
1983                 DEBUG(10, ("\n"));
1984         }
1985
1986         TALLOC_FREE(frame);
1987         return status;
1988 }
1989
1990 /********************************************************
1991  Internal interface to resolve a name into one IP address.
1992  Use this function if the string is either an IP address, DNS
1993  or host name or NetBIOS name. This uses the name switch in the
1994  smb.conf to determine the order of name resolution.
1995 *********************************************************/
1996
1997 bool resolve_name(const char *name,
1998                 struct sockaddr_storage *return_ss,
1999                 int name_type,
2000                 bool prefer_ipv4)
2001 {
2002         struct ip_service *ss_list = NULL;
2003         char *sitename = NULL;
2004         int count = 0;
2005
2006         if (is_ipaddress(name)) {
2007                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2008         }
2009
2010         sitename = sitename_fetch(lp_realm()); /* wild guess */
2011
2012         if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
2013                                                   &ss_list, &count,
2014                                                   lp_name_resolve_order()))) {
2015                 int i;
2016
2017                 if (prefer_ipv4) {
2018                         for (i=0; i<count; i++) {
2019                                 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2020                                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss) &&
2021                                                 (ss_list[i].ss.ss_family == AF_INET)) {
2022                                         *return_ss = ss_list[i].ss;
2023                                         SAFE_FREE(ss_list);
2024                                         SAFE_FREE(sitename);
2025                                         return True;
2026                                 }
2027                         }
2028                 }
2029
2030                 /* only return valid addresses for TCP connections */
2031                 for (i=0; i<count; i++) {
2032                         if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2033                                         !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2034                                 *return_ss = ss_list[i].ss;
2035                                 SAFE_FREE(ss_list);
2036                                 SAFE_FREE(sitename);
2037                                 return True;
2038                         }
2039                 }
2040         }
2041
2042         SAFE_FREE(ss_list);
2043         SAFE_FREE(sitename);
2044         return False;
2045 }
2046
2047 /********************************************************
2048  Internal interface to resolve a name into a list of IP addresses.
2049  Use this function if the string is either an IP address, DNS
2050  or host name or NetBIOS name. This uses the name switch in the
2051  smb.conf to determine the order of name resolution.
2052 *********************************************************/
2053
2054 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2055                 const char *name,
2056                 int name_type,
2057                 struct sockaddr_storage **return_ss_arr,
2058                 unsigned int *p_num_entries)
2059 {
2060         struct ip_service *ss_list = NULL;
2061         char *sitename = NULL;
2062         int count = 0;
2063         int i;
2064         unsigned int num_entries;
2065         NTSTATUS status;
2066
2067         *p_num_entries = 0;
2068         *return_ss_arr = NULL;
2069
2070         if (is_ipaddress(name)) {
2071                 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
2072                 if (!*return_ss_arr) {
2073                         return NT_STATUS_NO_MEMORY;
2074                 }
2075                 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2076                         TALLOC_FREE(*return_ss_arr);
2077                         return NT_STATUS_BAD_NETWORK_NAME;
2078                 }
2079                 *p_num_entries = 1;
2080                 return NT_STATUS_OK;
2081         }
2082
2083         sitename = sitename_fetch(lp_realm()); /* wild guess */
2084
2085         status = internal_resolve_name(name, name_type, sitename,
2086                                                   &ss_list, &count,
2087                                                   lp_name_resolve_order());
2088         SAFE_FREE(sitename);
2089
2090         if (!NT_STATUS_IS_OK(status)) {
2091                 return status;
2092         }
2093
2094         /* only return valid addresses for TCP connections */
2095         for (i=0, num_entries = 0; i<count; i++) {
2096                 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2097                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2098                         num_entries++;
2099                 }
2100         }
2101         if (num_entries == 0) {
2102                 SAFE_FREE(ss_list);
2103                 return NT_STATUS_BAD_NETWORK_NAME;
2104         }
2105
2106         *return_ss_arr = TALLOC_ARRAY(ctx,
2107                                 struct sockaddr_storage,
2108                                 num_entries);
2109         if (!(*return_ss_arr)) {
2110                 SAFE_FREE(ss_list);
2111                 return NT_STATUS_NO_MEMORY;
2112         }
2113
2114         for (i=0, num_entries = 0; i<count; i++) {
2115                 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
2116                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2117                         (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2118                 }
2119         }
2120
2121         status = NT_STATUS_OK;
2122         *p_num_entries = num_entries;
2123
2124         SAFE_FREE(ss_list);
2125         return NT_STATUS_OK;
2126 }
2127
2128 /********************************************************
2129  Find the IP address of the master browser or DMB for a workgroup.
2130 *********************************************************/
2131
2132 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2133 {
2134         struct ip_service *ip_list = NULL;
2135         int count = 0;
2136         NTSTATUS status;
2137
2138         if (lp_disable_netbios()) {
2139                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
2140                 return false;
2141         }
2142
2143         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
2144                                        lp_name_resolve_order());
2145         if (NT_STATUS_IS_OK(status)) {
2146                 *master_ss = ip_list[0].ss;
2147                 SAFE_FREE(ip_list);
2148                 return true;
2149         }
2150
2151         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
2152                                        lp_name_resolve_order());
2153         if (NT_STATUS_IS_OK(status)) {
2154                 *master_ss = ip_list[0].ss;
2155                 SAFE_FREE(ip_list);
2156                 return true;
2157         }
2158
2159         SAFE_FREE(ip_list);
2160         return false;
2161 }
2162
2163 /********************************************************
2164  Get the IP address list of the primary domain controller
2165  for a domain.
2166 *********************************************************/
2167
2168 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
2169 {
2170         struct ip_service *ip_list = NULL;
2171         int count = 0;
2172         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2173
2174         /* Look up #1B name */
2175
2176         if (lp_security() == SEC_ADS) {
2177                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2178                                                &count, "ads");
2179         }
2180
2181         if (!NT_STATUS_IS_OK(status) || count == 0) {
2182                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2183                                                &count,
2184                                                lp_name_resolve_order());
2185                 if (!NT_STATUS_IS_OK(status)) {
2186                         return false;
2187                 }
2188         }
2189
2190         /* if we get more than 1 IP back we have to assume it is a
2191            multi-homed PDC and not a mess up */
2192
2193         if ( count > 1 ) {
2194                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
2195                 sort_service_list(ip_list, count);
2196         }
2197
2198         *pss = ip_list[0].ss;
2199         SAFE_FREE(ip_list);
2200         return true;
2201 }
2202
2203 /* Private enum type for lookups. */
2204
2205 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
2206
2207 /********************************************************
2208  Get the IP address list of the domain controllers for
2209  a domain.
2210 *********************************************************/
2211
2212 static NTSTATUS get_dc_list(const char *domain,
2213                         const char *sitename,
2214                         struct ip_service **ip_list,
2215                         int *count,
2216                         enum dc_lookup_type lookup_type,
2217                         bool *ordered)
2218 {
2219         char *resolve_order = NULL;
2220         char *saf_servername = NULL;
2221         char *pserver = NULL;
2222         const char *p;
2223         char *port_str = NULL;
2224         int port;
2225         char *name;
2226         int num_addresses = 0;
2227         int  local_count, i, j;
2228         struct ip_service *return_iplist = NULL;
2229         struct ip_service *auto_ip_list = NULL;
2230         bool done_auto_lookup = false;
2231         int auto_count = 0;
2232         NTSTATUS status;
2233         TALLOC_CTX *ctx = talloc_init("get_dc_list");
2234
2235         *ip_list = NULL;
2236         *count = 0;
2237
2238         if (!ctx) {
2239                 return NT_STATUS_NO_MEMORY;
2240         }
2241
2242         *ordered = False;
2243
2244         /* if we are restricted to solely using DNS for looking
2245            up a domain controller, make sure that host lookups
2246            are enabled for the 'name resolve order'.  If host lookups
2247            are disabled and ads_only is True, then set the string to
2248            NULL. */
2249
2250         resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
2251         if (!resolve_order) {
2252                 status = NT_STATUS_NO_MEMORY;
2253                 goto out;
2254         }
2255         strlower_m(resolve_order);
2256         if (lookup_type == DC_ADS_ONLY)  {
2257                 if (strstr( resolve_order, "host")) {
2258                         resolve_order = talloc_strdup(ctx, "ads");
2259
2260                         /* DNS SRV lookups used by the ads resolver
2261                            are already sorted by priority and weight */
2262                         *ordered = true;
2263                 } else {
2264                         resolve_order = talloc_strdup(ctx, "NULL");
2265                 }
2266         } else if (lookup_type == DC_KDC_ONLY) {
2267                 /* DNS SRV lookups used by the ads/kdc resolver
2268                    are already sorted by priority and weight */
2269                 *ordered = true;
2270                 resolve_order = talloc_strdup(ctx, "kdc");
2271         }
2272         if (!resolve_order) {
2273                 status = NT_STATUS_NO_MEMORY;
2274                 goto out;
2275         }
2276
2277         /* fetch the server we have affinity for.  Add the
2278            'password server' list to a search for our domain controllers */
2279
2280         saf_servername = saf_fetch( domain);
2281
2282         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
2283                 pserver = talloc_asprintf(ctx, "%s, %s",
2284                         saf_servername ? saf_servername : "",
2285                         lp_passwordserver());
2286         } else {
2287                 pserver = talloc_asprintf(ctx, "%s, *",
2288                         saf_servername ? saf_servername : "");
2289         }
2290
2291         SAFE_FREE(saf_servername);
2292         if (!pserver) {
2293                 status = NT_STATUS_NO_MEMORY;
2294                 goto out;
2295         }
2296
2297         /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
2298
2299         if (!*pserver ) {
2300                 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
2301                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2302                                              count, resolve_order);
2303                 goto out;
2304         }
2305
2306         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
2307
2308         /*
2309          * if '*' appears in the "password server" list then add
2310          * an auto lookup to the list of manually configured
2311          * DC's.  If any DC is listed by name, then the list should be
2312          * considered to be ordered
2313          */
2314
2315         p = pserver;
2316         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2317                 if (!done_auto_lookup && strequal(name, "*")) {
2318                         status = internal_resolve_name(domain, 0x1C, sitename,
2319                                                        &auto_ip_list,
2320                                                        &auto_count,
2321                                                        resolve_order);
2322                         if (NT_STATUS_IS_OK(status)) {
2323                                 num_addresses += auto_count;
2324                         }
2325                         done_auto_lookup = true;
2326                         DEBUG(8,("Adding %d DC's from auto lookup\n",
2327                                                 auto_count));
2328                 } else  {
2329                         num_addresses++;
2330                 }
2331         }
2332
2333         /* if we have no addresses and haven't done the auto lookup, then
2334            just return the list of DC's.  Or maybe we just failed. */
2335
2336         if ((num_addresses == 0)) {
2337                 if (done_auto_lookup) {
2338                         DEBUG(4,("get_dc_list: no servers found\n"));
2339                         status = NT_STATUS_NO_LOGON_SERVERS;
2340                         goto out;
2341                 }
2342                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2343                                              count, resolve_order);
2344                 goto out;
2345         }
2346
2347         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
2348                                         num_addresses)) == NULL) {
2349                 DEBUG(3,("get_dc_list: malloc fail !\n"));
2350                 status = NT_STATUS_NO_MEMORY;
2351                 goto out;
2352         }
2353
2354         p = pserver;
2355         local_count = 0;
2356
2357         /* fill in the return list now with real IP's */
2358
2359         while ((local_count<num_addresses) &&
2360                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2361                 struct sockaddr_storage name_ss;
2362
2363                 /* copy any addersses from the auto lookup */
2364
2365                 if (strequal(name, "*")) {
2366                         for (j=0; j<auto_count; j++) {
2367                                 char addr[INET6_ADDRSTRLEN];
2368                                 print_sockaddr(addr,
2369                                                 sizeof(addr),
2370                                                 &auto_ip_list[j].ss);
2371                                 /* Check for and don't copy any
2372                                  * known bad DC IP's. */
2373                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
2374                                                 domain,
2375                                                 addr))) {
2376                                         DEBUG(5,("get_dc_list: "
2377                                                 "negative entry %s removed "
2378                                                 "from DC list\n",
2379                                                 addr));
2380                                         continue;
2381                                 }
2382                                 return_iplist[local_count].ss =
2383                                         auto_ip_list[j].ss;
2384                                 return_iplist[local_count].port =
2385                                         auto_ip_list[j].port;
2386                                 local_count++;
2387                         }
2388                         continue;
2389                 }
2390
2391                 /* added support for address:port syntax for ads
2392                  * (not that I think anyone will ever run the LDAP
2393                  * server in an AD domain on something other than
2394                  * port 389 */
2395
2396                 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
2397                 if ((port_str=strchr(name, ':')) != NULL) {
2398                         *port_str = '\0';
2399                         port_str++;
2400                         port = atoi(port_str);
2401                 }
2402
2403                 /* explicit lookup; resolve_name() will
2404                  * handle names & IP addresses */
2405                 if (resolve_name( name, &name_ss, 0x20, true )) {
2406                         char addr[INET6_ADDRSTRLEN];
2407                         print_sockaddr(addr,
2408                                         sizeof(addr),
2409                                         &name_ss);
2410
2411                         /* Check for and don't copy any known bad DC IP's. */
2412                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2413                                                         addr)) ) {
2414                                 DEBUG(5,("get_dc_list: negative entry %s "
2415                                         "removed from DC list\n",
2416                                         name ));
2417                                 continue;
2418                         }
2419
2420                         return_iplist[local_count].ss = name_ss;
2421                         return_iplist[local_count].port = port;
2422                         local_count++;
2423                         *ordered = true;
2424                 }
2425         }
2426
2427         /* need to remove duplicates in the list if we have any
2428            explicit password servers */
2429
2430         if (local_count) {
2431                 local_count = remove_duplicate_addrs2(return_iplist,
2432                                 local_count );
2433         }
2434
2435         /* For DC's we always prioritize IPv4 due to W2K3 not
2436          * supporting LDAP, KRB5 or CLDAP over IPv6. */
2437
2438         if (local_count && return_iplist) {
2439                 prioritize_ipv4_list(return_iplist, local_count);
2440         }
2441
2442         if ( DEBUGLEVEL >= 4 ) {
2443                 DEBUG(4,("get_dc_list: returning %d ip addresses "
2444                                 "in an %sordered list\n",
2445                                 local_count,
2446                                 *ordered ? "":"un"));
2447                 DEBUG(4,("get_dc_list: "));
2448                 for ( i=0; i<local_count; i++ ) {
2449                         char addr[INET6_ADDRSTRLEN];
2450                         print_sockaddr(addr,
2451                                         sizeof(addr),
2452                                         &return_iplist[i].ss);
2453                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2454                 }
2455                 DEBUGADD(4,("\n"));
2456         }
2457
2458         *ip_list = return_iplist;
2459         *count = local_count;
2460
2461         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2462
2463   out:
2464
2465         if (!NT_STATUS_IS_OK(status)) {
2466                 SAFE_FREE(return_iplist);
2467                 *ip_list = NULL;
2468                 *count = 0;
2469         }
2470
2471         SAFE_FREE(auto_ip_list);
2472         TALLOC_FREE(ctx);
2473         return status;
2474 }
2475
2476 /*********************************************************************
2477  Small wrapper function to get the DC list and sort it if neccessary.
2478 *********************************************************************/
2479
2480 NTSTATUS get_sorted_dc_list( const char *domain,
2481                         const char *sitename,
2482                         struct ip_service **ip_list,
2483                         int *count,
2484                         bool ads_only )
2485 {
2486         bool ordered = false;
2487         NTSTATUS status;
2488         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2489
2490         *ip_list = NULL;
2491         *count = 0;
2492
2493         DEBUG(8,("get_sorted_dc_list: attempting lookup "
2494                 "for name %s (sitename %s) using [%s]\n",
2495                 domain,
2496                 sitename ? sitename : "NULL",
2497                 (ads_only ? "ads" : lp_name_resolve_order())));
2498
2499         if (ads_only) {
2500                 lookup_type = DC_ADS_ONLY;
2501         }
2502
2503         status = get_dc_list(domain, sitename, ip_list,
2504                         count, lookup_type, &ordered);
2505         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
2506             && sitename) {
2507                 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
2508                          " in site %s, fallback to all servers\n",
2509                          domain, sitename));
2510                 status = get_dc_list(domain, NULL, ip_list,
2511                                      count, lookup_type, &ordered);
2512         }
2513
2514         if (!NT_STATUS_IS_OK(status)) {
2515                 SAFE_FREE(*ip_list);
2516                 *count = 0;
2517                 return status;
2518         }
2519
2520         /* only sort if we don't already have an ordered list */
2521         if (!ordered) {
2522                 sort_service_list(*ip_list, *count);
2523         }
2524
2525         return NT_STATUS_OK;
2526 }
2527
2528 /*********************************************************************
2529  Get the KDC list - re-use all the logic in get_dc_list.
2530 *********************************************************************/
2531
2532 NTSTATUS get_kdc_list( const char *realm,
2533                         const char *sitename,
2534                         struct ip_service **ip_list,
2535                         int *count)
2536 {
2537         bool ordered;
2538         NTSTATUS status;
2539
2540         *count = 0;
2541         *ip_list = NULL;
2542
2543         status = get_dc_list(realm, sitename, ip_list,
2544                         count, DC_KDC_ONLY, &ordered);
2545
2546         if (!NT_STATUS_IS_OK(status)) {
2547                 SAFE_FREE(*ip_list);
2548                 *count = 0;
2549                 return status;
2550         }
2551
2552         /* only sort if we don't already have an ordered list */
2553         if ( !ordered ) {
2554                 sort_service_list(*ip_list, *count);
2555         }
2556
2557         return NT_STATUS_OK;
2558 }