s3: Fix a typed-punned warning
[kai/samba-autobuild/.git] / source3 / nmbd / nmbd_packets.c
1 /* 
2    Unix SMB/CIFS implementation.
3    NBT netbios routines and daemon - version 2
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Luke Kenneth Casson Leighton 1994-1998
6    Copyright (C) Jeremy Allison 1994-2003
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "nmbd/nmbd.h"
24 #include "../lib/util/select.h"
25
26 extern int ClientNMB;
27 extern int ClientDGRAM;
28 extern int global_nmb_port;
29
30 extern int num_response_packets;
31
32 bool rescan_listen_set = False;
33
34 static struct nb_packet_server *packet_server;
35
36 bool nmbd_init_packet_server(void)
37 {
38         NTSTATUS status;
39
40         status = nb_packet_server_create(
41                 NULL, nmbd_event_context(),
42                 lp_parm_int(-1, "nmbd", "unexpected_clients", 200),
43                 &packet_server);
44         if (!NT_STATUS_IS_OK(status)) {
45                 DEBUG(0, ("ERROR: nb_packet_server_create failed: %s\n",
46                           nt_errstr(status)));
47                 return false;
48         }
49         return true;
50 }
51
52
53 /*******************************************************************
54   The global packet linked-list. Incoming entries are 
55   added to the end of this list. It is supposed to remain fairly 
56   short so we won't bother with an end pointer.
57 ******************************************************************/
58
59 static struct packet_struct *packet_queue = NULL;
60
61 /***************************************************************************
62 Utility function to find the specific fd to send a packet out on.
63 **************************************************************************/
64
65 static int find_subnet_fd_for_address( struct in_addr local_ip )
66 {
67         struct subnet_record *subrec;
68
69         for( subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
70                 if(ip_equal_v4(local_ip, subrec->myip))
71                         return subrec->nmb_sock;
72
73         return ClientNMB;
74 }
75
76 /***************************************************************************
77 Utility function to find the specific fd to send a mailslot packet out on.
78 **************************************************************************/
79
80 static int find_subnet_mailslot_fd_for_address( struct in_addr local_ip )
81 {
82         struct subnet_record *subrec;
83
84         for( subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
85                 if(ip_equal_v4(local_ip, subrec->myip))
86                         return subrec->dgram_sock;
87
88         return ClientDGRAM;
89 }
90
91 /***************************************************************************
92 Get/Set problematic nb_flags as network byte order 16 bit int.
93 **************************************************************************/
94
95 uint16 get_nb_flags(char *buf)
96 {
97         return ((((uint16)*buf)&0xFFFF) & NB_FLGMSK);
98 }
99
100 void set_nb_flags(char *buf, uint16 nb_flags)
101 {
102         *buf++ = ((nb_flags & NB_FLGMSK) & 0xFF);
103         *buf = '\0';
104 }
105
106 /***************************************************************************
107 Dumps out the browse packet data.
108 **************************************************************************/
109
110 static void debug_browse_data(char *outbuf, int len)
111 {
112         int i,j;
113
114         DEBUG( 4, ( "debug_browse_data():\n" ) );
115         for (i = 0; i < len; i+= 16) {
116                 DEBUGADD( 4, ( "%3x char ", i ) );
117
118                 for (j = 0; j < 16; j++) {
119                         unsigned char x;
120                         if (i+j >= len)
121                                 break;
122
123                         x = outbuf[i+j];
124                         if (x < 32 || x > 127) 
125                                 x = '.';
126
127                         DEBUGADD( 4, ( "%c", x ) );
128                 }
129
130                 DEBUGADD( 4, ( "%*s hex", 16-j, "" ) );
131
132                 for (j = 0; j < 16; j++) {
133                         if (i+j >= len) 
134                                 break;
135                         DEBUGADD( 4, ( " %02x", (unsigned char)outbuf[i+j] ) );
136                 }
137
138                 DEBUGADD( 4, ("\n") );
139         }
140 }
141
142 /***************************************************************************
143   Generates the unique transaction identifier
144 **************************************************************************/
145
146 static uint16 name_trn_id=0;
147
148 static uint16 generate_name_trn_id(void)
149 {
150         if (!name_trn_id) {
151                 name_trn_id = ((unsigned)time(NULL)%(unsigned)0x7FFF) + ((unsigned)sys_getpid()%(unsigned)100);
152         }
153         name_trn_id = (name_trn_id+1) % (unsigned)0x7FFF;
154         return name_trn_id;
155 }
156
157 /***************************************************************************
158  Either loops back or sends out a completed NetBIOS packet.
159 **************************************************************************/
160
161 static bool send_netbios_packet(struct packet_struct *p)
162 {
163         bool loopback_this_packet = False;
164
165         /* Check if we are sending to or from ourselves as a WINS server. */
166         if(ismyip_v4(p->ip) && (p->port == global_nmb_port))
167                 loopback_this_packet = True;
168
169         if(loopback_this_packet) {
170                 struct packet_struct *lo_packet = NULL;
171                 DEBUG(5,("send_netbios_packet: sending packet to ourselves.\n"));
172                 if((lo_packet = copy_packet(p)) == NULL)
173                         return False;
174                 queue_packet(lo_packet);
175         } else if (!send_packet(p)) {
176                 DEBUG(0,("send_netbios_packet: send_packet() to IP %s port %d failed\n",
177                         inet_ntoa(p->ip),p->port));
178                 return False;
179         }
180
181         return True;
182
183
184 /***************************************************************************
185  Sets up the common elements of an outgoing NetBIOS packet.
186
187  Note: do not attempt to rationalise whether rec_des should be set or not
188  in a particular situation. Just follow rfc_1002 or look at examples from WinXX.
189  It does NOT follow the rule that requests to the wins server always have
190  rec_des true. See for example name releases and refreshes
191 **************************************************************************/
192
193 static struct packet_struct *create_and_init_netbios_packet(struct nmb_name *nmbname,
194                                                             bool bcast, bool rec_des,
195                                                             struct in_addr to_ip)
196 {
197         struct packet_struct *packet = NULL;
198         struct nmb_packet *nmb = NULL;
199
200         /* Allocate the packet_struct we will return. */
201         if((packet = SMB_MALLOC_P(struct packet_struct)) == NULL) {
202                 DEBUG(0,("create_and_init_netbios_packet: malloc fail (1) for packet struct.\n"));
203                 return NULL;
204         }
205
206         memset((char *)packet,'\0',sizeof(*packet));
207
208         nmb = &packet->packet.nmb;
209
210         nmb->header.name_trn_id = generate_name_trn_id();
211         nmb->header.response = False;
212         nmb->header.nm_flags.recursion_desired = rec_des;
213         nmb->header.nm_flags.recursion_available = False;
214         nmb->header.nm_flags.trunc = False;
215         nmb->header.nm_flags.authoritative = False;
216         nmb->header.nm_flags.bcast = bcast;
217
218         nmb->header.rcode = 0;
219         nmb->header.qdcount = 1;
220         nmb->header.ancount = 0;
221         nmb->header.nscount = 0;
222
223         nmb->question.question_name = *nmbname;
224         nmb->question.question_type = QUESTION_TYPE_NB_QUERY;
225         nmb->question.question_class = QUESTION_CLASS_IN;
226
227         packet->ip = to_ip;
228         packet->port = NMB_PORT;
229         packet->recv_fd = -1;
230         packet->send_fd = ClientNMB;
231         packet->timestamp = time(NULL);
232         packet->packet_type = NMB_PACKET;
233         packet->locked = False;
234
235         return packet; /* Caller must free. */
236 }
237
238 /***************************************************************************
239  Sets up the common elements of register, refresh or release packet.
240 **************************************************************************/
241
242 static bool create_and_init_additional_record(struct packet_struct *packet,
243                                                      uint16 nb_flags,
244                                                      const struct in_addr *register_ip)
245 {
246         struct nmb_packet *nmb = &packet->packet.nmb;
247
248         if((nmb->additional = SMB_MALLOC_P(struct res_rec)) == NULL) {
249                 DEBUG(0,("create_and_init_additional_record: malloc fail for additional record.\n"));
250                 return False;
251         }
252
253         memset((char *)nmb->additional,'\0',sizeof(struct res_rec));
254
255         nmb->additional->rr_name  = nmb->question.question_name;
256         nmb->additional->rr_type  = RR_TYPE_NB;
257         nmb->additional->rr_class = RR_CLASS_IN;
258
259         /* See RFC 1002, sections 5.1.1.1, 5.1.1.2 and 5.1.1.3 */
260         if (nmb->header.nm_flags.bcast)
261                 nmb->additional->ttl = PERMANENT_TTL;
262         else
263                 nmb->additional->ttl = lp_max_ttl();
264
265         nmb->additional->rdlength = 6;
266
267         set_nb_flags(nmb->additional->rdata,nb_flags);
268
269         /* Set the address for the name we are registering. */
270         putip(&nmb->additional->rdata[2], register_ip);
271
272         /* 
273            it turns out that Jeremys code was correct, we are supposed
274            to send registrations from the IP we are registering. The
275            trick is what to do on timeouts! When we send on a
276            non-routable IP then the reply will timeout, and we should
277            treat this as success, not failure. That means we go into
278            our standard refresh cycle for that name which copes nicely
279            with disconnected networks.
280         */
281         packet->recv_fd = -1;
282         packet->send_fd = find_subnet_fd_for_address(*register_ip);
283
284         return True;
285 }
286
287 /***************************************************************************
288  Sends out a name query.
289 **************************************************************************/
290
291 static bool initiate_name_query_packet( struct packet_struct *packet)
292 {
293         struct nmb_packet *nmb = NULL;
294
295         nmb = &packet->packet.nmb;
296
297         nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
298         nmb->header.arcount = 0;
299
300         nmb->header.nm_flags.recursion_desired = True;
301
302         DEBUG(4,("initiate_name_query_packet: sending query for name %s (bcast=%s) to IP %s\n",
303                 nmb_namestr(&nmb->question.question_name), 
304                 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
305
306         return send_netbios_packet( packet );
307 }
308
309 /***************************************************************************
310  Sends out a name query - from a WINS server. 
311 **************************************************************************/
312
313 static bool initiate_name_query_packet_from_wins_server( struct packet_struct *packet)
314 {   
315         struct nmb_packet *nmb = NULL;
316
317         nmb = &packet->packet.nmb;
318
319         nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
320         nmb->header.arcount = 0;
321
322         nmb->header.nm_flags.recursion_desired = False;
323
324         DEBUG(4,("initiate_name_query_packet_from_wins_server: sending query for name %s (bcast=%s) to IP %s\n",
325                 nmb_namestr(&nmb->question.question_name),
326                 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
327
328         return send_netbios_packet( packet );
329
330
331 /***************************************************************************
332  Sends out a name register.
333 **************************************************************************/
334
335 static bool initiate_name_register_packet( struct packet_struct *packet,
336                                     uint16 nb_flags, const struct in_addr *register_ip)
337 {
338         struct nmb_packet *nmb = &packet->packet.nmb;
339
340         nmb->header.opcode = NMB_NAME_REG_OPCODE;
341         nmb->header.arcount = 1;
342
343         nmb->header.nm_flags.recursion_desired = True;
344
345         if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
346                 return False;
347
348         DEBUG(4,("initiate_name_register_packet: sending registration for name %s (bcast=%s) to IP %s\n",
349                 nmb_namestr(&nmb->additional->rr_name),
350                 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
351
352         return send_netbios_packet( packet );
353 }
354
355 /***************************************************************************
356  Sends out a multihomed name register.
357 **************************************************************************/
358
359 static bool initiate_multihomed_name_register_packet(struct packet_struct *packet,
360                                                      uint16 nb_flags, struct in_addr *register_ip)
361 {
362         struct nmb_packet *nmb = &packet->packet.nmb;
363         fstring second_ip_buf;
364
365         fstrcpy(second_ip_buf, inet_ntoa(packet->ip));
366
367         nmb->header.opcode = NMB_NAME_MULTIHOMED_REG_OPCODE;
368         nmb->header.arcount = 1;
369
370         nmb->header.nm_flags.recursion_desired = True;
371
372         if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
373                 return False;
374
375         DEBUG(4,("initiate_multihomed_name_register_packet: sending registration \
376 for name %s IP %s (bcast=%s) to IP %s\n",
377                  nmb_namestr(&nmb->additional->rr_name), inet_ntoa(*register_ip),
378                  BOOLSTR(nmb->header.nm_flags.bcast), second_ip_buf ));
379
380         return send_netbios_packet( packet );
381
382
383 /***************************************************************************
384  Sends out a name refresh.
385 **************************************************************************/
386
387 static bool initiate_name_refresh_packet( struct packet_struct *packet,
388                                    uint16 nb_flags, struct in_addr *refresh_ip)
389 {
390         struct nmb_packet *nmb = &packet->packet.nmb;
391
392         nmb->header.opcode = NMB_NAME_REFRESH_OPCODE_8;
393         nmb->header.arcount = 1;
394
395         nmb->header.nm_flags.recursion_desired = False;
396
397         if(create_and_init_additional_record(packet, nb_flags, refresh_ip) == False)
398                 return False;
399
400         DEBUG(4,("initiate_name_refresh_packet: sending refresh for name %s (bcast=%s) to IP %s\n",
401                 nmb_namestr(&nmb->additional->rr_name),
402                 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
403
404         return send_netbios_packet( packet );
405
406
407 /***************************************************************************
408  Sends out a name release.
409 **************************************************************************/
410
411 static bool initiate_name_release_packet( struct packet_struct *packet,
412                                    uint16 nb_flags, struct in_addr *release_ip)
413 {
414         struct nmb_packet *nmb = &packet->packet.nmb;
415
416         nmb->header.opcode = NMB_NAME_RELEASE_OPCODE;
417         nmb->header.arcount = 1;
418
419         nmb->header.nm_flags.recursion_desired = False;
420
421         if(create_and_init_additional_record(packet, nb_flags, release_ip) == False)
422                 return False;
423
424         DEBUG(4,("initiate_name_release_packet: sending release for name %s (bcast=%s) to IP %s\n",
425                 nmb_namestr(&nmb->additional->rr_name),
426                 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
427
428         return send_netbios_packet( packet );
429
430
431 /***************************************************************************
432  Sends out a node status.
433 **************************************************************************/
434
435 static bool initiate_node_status_packet( struct packet_struct *packet )
436 {
437         struct nmb_packet *nmb = &packet->packet.nmb;
438
439         nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
440         nmb->header.arcount = 0;
441
442         nmb->header.nm_flags.recursion_desired = False;
443
444         nmb->question.question_type = QUESTION_TYPE_NB_STATUS;
445
446         DEBUG(4,("initiate_node_status_packet: sending node status request for name %s to IP %s\n",
447                 nmb_namestr(&nmb->question.question_name),
448                 inet_ntoa(packet->ip)));
449
450         return send_netbios_packet( packet );
451 }
452
453 /****************************************************************************
454   Simplification functions for queuing standard packets.
455   These should be the only publicly callable functions for sending
456   out packets.
457 ****************************************************************************/
458
459 /****************************************************************************
460  Assertion - we should never be sending nmbd packets on the remote
461  broadcast subnet.
462 ****************************************************************************/
463
464 static bool assert_check_subnet(struct subnet_record *subrec)
465 {
466         if( subrec == remote_broadcast_subnet) {
467                 DEBUG(0,("assert_check_subnet: Attempt to send packet on remote broadcast subnet. \
468 This is a bug.\n"));
469                 return True;
470         }
471         return False;
472 }
473
474 /****************************************************************************
475  Queue a register name packet to the broadcast address of a subnet.
476 ****************************************************************************/
477
478 struct response_record *queue_register_name( struct subnet_record *subrec,
479                           response_function resp_fn,
480                           timeout_response_function timeout_fn,
481                           register_name_success_function success_fn,
482                           register_name_fail_function fail_fn,
483                           struct userdata_struct *userdata,
484                           struct nmb_name *nmbname,
485                           uint16 nb_flags)
486 {
487         struct packet_struct *p;
488         struct response_record *rrec;
489         struct sockaddr_storage ss;
490         const struct sockaddr_storage *pss = NULL;
491         if(assert_check_subnet(subrec))
492                 return NULL;
493
494         /* note that all name registration requests have RD set (rfc1002 - section 4.2.2 */
495         if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), True,
496                                 subrec->bcast_ip)) == NULL)
497                 return NULL;
498
499         in_addr_to_sockaddr_storage(&ss, subrec->bcast_ip);
500         pss = iface_ip((struct sockaddr *)(void *)&ss);
501         if (!pss || pss->ss_family != AF_INET) {
502                 p->locked = False;
503                 free_packet(p);
504                 return NULL;
505         }
506
507         if(initiate_name_register_packet(p, nb_flags,
508                         &((const struct sockaddr_in *)pss)->sin_addr) == False) {
509                 p->locked = False;
510                 free_packet(p);
511                 return NULL;
512         }
513
514         if((rrec = make_response_record(subrec,        /* subnet record. */
515                                 p,                     /* packet we sent. */
516                                 resp_fn,               /* function to call on response. */
517                                 timeout_fn,            /* function to call on timeout. */
518                                 (success_function)success_fn,            /* function to call on operation success. */
519                                 (fail_function)fail_fn,               /* function to call on operation fail. */
520                                 userdata)) == NULL)  {
521                 p->locked = False;
522                 free_packet(p);
523                 return NULL;
524         }
525
526         return rrec;
527 }
528
529 /****************************************************************************
530  Queue a refresh name packet to the broadcast address of a subnet.
531 ****************************************************************************/
532
533 void queue_wins_refresh(struct nmb_name *nmbname,
534                         response_function resp_fn,
535                         timeout_response_function timeout_fn,
536                         uint16 nb_flags,
537                         struct in_addr refresh_ip,
538                         const char *tag)
539 {
540         struct packet_struct *p;
541         struct response_record *rrec;
542         struct in_addr wins_ip;
543         struct userdata_struct *userdata;
544         fstring ip_str;
545
546         wins_ip = wins_srv_ip_tag(tag, refresh_ip);
547
548         if ((p = create_and_init_netbios_packet(nmbname, False, False, wins_ip)) == NULL) {
549                 return;
550         }
551
552         if (!initiate_name_refresh_packet(p, nb_flags, &refresh_ip)) {
553                 p->locked = False;
554                 free_packet(p);
555                 return;
556         }
557
558         fstrcpy(ip_str, inet_ntoa(refresh_ip));
559
560         DEBUG(6,("Refreshing name %s IP %s with WINS server %s using tag '%s'\n",
561                  nmb_namestr(nmbname), ip_str, inet_ntoa(wins_ip), tag));
562
563         userdata = (struct userdata_struct *)SMB_MALLOC(sizeof(*userdata) + strlen(tag) + 1);
564         if (!userdata) {
565                 p->locked = False;
566                 free_packet(p);
567                 DEBUG(0,("Failed to allocate userdata structure!\n"));
568                 return;
569         }
570         ZERO_STRUCTP(userdata);
571         userdata->userdata_len = strlen(tag) + 1;
572         strlcpy(userdata->data, tag, userdata->userdata_len);   
573
574         if ((rrec = make_response_record(unicast_subnet,
575                                          p,
576                                          resp_fn, timeout_fn,
577                                          NULL,
578                                          NULL,
579                                          userdata)) == NULL) {
580                 p->locked = False;
581                 free_packet(p);
582                 return;
583         }
584
585         free(userdata);
586
587         /* we don't want to repeat refresh packets */
588         rrec->repeat_count = 0;
589 }
590
591
592 /****************************************************************************
593  Queue a multihomed register name packet to a given WINS server IP
594 ****************************************************************************/
595
596 struct response_record *queue_register_multihomed_name( struct subnet_record *subrec,
597                                                         response_function resp_fn,
598                                                         timeout_response_function timeout_fn,
599                                                         register_name_success_function success_fn,
600                                                         register_name_fail_function fail_fn,
601                                                         struct userdata_struct *userdata,
602                                                         struct nmb_name *nmbname,
603                                                         uint16 nb_flags,
604                                                         struct in_addr register_ip,
605                                                         struct in_addr wins_ip)
606 {
607         struct packet_struct *p;
608         struct response_record *rrec;
609         bool ret;
610
611         /* Sanity check. */
612         if(subrec != unicast_subnet) {
613                 DEBUG(0,("queue_register_multihomed_name: should only be done on \
614 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
615                 return NULL;
616         }
617
618         if(assert_check_subnet(subrec))
619                 return NULL;
620
621         if ((p = create_and_init_netbios_packet(nmbname, False, True, wins_ip)) == NULL)
622                 return NULL;
623
624         if (nb_flags & NB_GROUP)
625                 ret = initiate_name_register_packet( p, nb_flags, &register_ip);
626         else
627                 ret = initiate_multihomed_name_register_packet(p, nb_flags, &register_ip);
628
629         if (ret == False) {  
630                 p->locked = False;
631                 free_packet(p);
632                 return NULL;
633         }  
634
635         if ((rrec = make_response_record(subrec,    /* subnet record. */
636                                          p,                     /* packet we sent. */
637                                          resp_fn,               /* function to call on response. */
638                                          timeout_fn,            /* function to call on timeout. */
639                                          (success_function)success_fn, /* function to call on operation success. */
640                                          (fail_function)fail_fn,       /* function to call on operation fail. */
641                                          userdata)) == NULL) {  
642                 p->locked = False;
643                 free_packet(p);
644                 return NULL;
645         }  
646
647         return rrec;
648 }
649
650 /****************************************************************************
651  Queue a release name packet to the broadcast address of a subnet.
652 ****************************************************************************/
653
654 struct response_record *queue_release_name( struct subnet_record *subrec,
655                                             response_function resp_fn,
656                                             timeout_response_function timeout_fn,
657                                             release_name_success_function success_fn,
658                                             release_name_fail_function fail_fn,
659                                             struct userdata_struct *userdata,
660                                             struct nmb_name *nmbname,
661                                             uint16 nb_flags,
662                                             struct in_addr release_ip,
663                                             struct in_addr dest_ip)
664 {
665         struct packet_struct *p;
666         struct response_record *rrec;
667
668         if(assert_check_subnet(subrec))
669                 return NULL;
670
671         if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), False, dest_ip)) == NULL)
672                 return NULL;
673
674         if(initiate_name_release_packet( p, nb_flags, &release_ip) == False) {
675                 p->locked = False;
676                 free_packet(p);
677                 return NULL;
678         }
679
680         if((rrec = make_response_record(subrec,                /* subnet record. */
681                                         p,                     /* packet we sent. */
682                                         resp_fn,               /* function to call on response. */
683                                         timeout_fn,            /* function to call on timeout. */
684                                         (success_function)success_fn,            /* function to call on operation success. */
685                                         (fail_function)fail_fn,               /* function to call on operation fail. */
686                                         userdata)) == NULL)  {
687                 p->locked = False;
688                 free_packet(p);
689                 return NULL;
690         }
691
692         /*
693          * For a broadcast release packet, only send once.
694          * This will cause us to remove the name asap. JRA.
695          */
696
697         if (subrec != unicast_subnet) {
698                 rrec->repeat_count = 0;
699                 rrec->repeat_time = 0;
700         }
701
702         return rrec;
703 }
704
705 /****************************************************************************
706  Queue a query name packet to the broadcast address of a subnet.
707 ****************************************************************************/
708
709 struct response_record *queue_query_name( struct subnet_record *subrec,
710                           response_function resp_fn,
711                           timeout_response_function timeout_fn,
712                           query_name_success_function success_fn,
713                           query_name_fail_function fail_fn,
714                           struct userdata_struct *userdata,
715                           struct nmb_name *nmbname)
716 {
717         struct packet_struct *p;
718         struct response_record *rrec;
719         struct in_addr to_ip;
720
721         if(assert_check_subnet(subrec))
722                 return NULL;
723
724         to_ip = subrec->bcast_ip;
725
726         /* queries to the WINS server turn up here as queries to IP 0.0.0.0 
727                         These need to be handled a bit differently */
728         if (subrec->type == UNICAST_SUBNET && is_zero_ip_v4(to_ip)) {
729                 /* What we really need to do is loop over each of our wins
730                  * servers and wins server tags here, but that just doesn't
731                  * fit our architecture at the moment (userdata may already
732                  * be used when we get here). For now we just query the first
733                  * active wins server on the first tag.
734                  */ 
735                 char **tags = wins_srv_tags();
736                 if (!tags) {
737                         return NULL;
738                 }
739                 to_ip = wins_srv_ip_tag(tags[0], to_ip);
740                 wins_srv_tags_free(tags);
741         }
742
743         if(( p = create_and_init_netbios_packet(nmbname, 
744                                         (subrec != unicast_subnet), 
745                                         (subrec == unicast_subnet), 
746                                         to_ip)) == NULL)
747                 return NULL;
748
749         if(lp_bind_interfaces_only()) {
750                 int i;
751
752                 DEBUG(10,("queue_query_name: bind_interfaces_only is set, looking for suitable source IP\n"));
753                 for(i = 0; i < iface_count(); i++) {
754                         const struct in_addr *ifip = iface_n_ip_v4(i);
755
756                         if (ifip == NULL) {
757                                 DEBUG(0,("queue_query_name: interface %d has NULL IP address !\n", i));
758                                 continue;
759                         }
760
761                         if (is_loopback_ip_v4(*ifip)) {
762                                 DEBUG(5,("queue_query_name: ignoring loopback interface (%d)\n", i));
763                                 continue;
764                         }
765
766                         DEBUG(10,("queue_query_name: using source IP %s\n",inet_ntoa(*ifip)));
767                                 p->send_fd = find_subnet_fd_for_address( *ifip );
768                                 break;
769                 }
770         }
771
772         if(initiate_name_query_packet( p ) == False) {
773                 p->locked = False;
774                 free_packet(p);
775                 return NULL;
776         }
777
778         if((rrec = make_response_record(subrec,                /* subnet record. */
779                                         p,                     /* packet we sent. */
780                                         resp_fn,               /* function to call on response. */
781                                         timeout_fn,            /* function to call on timeout. */
782                                         (success_function)success_fn,            /* function to call on operation success. */
783                                         (fail_function)fail_fn,               /* function to call on operation fail. */
784                                         userdata)) == NULL) {
785                 p->locked = False;
786                 free_packet(p);
787                 return NULL;
788         }
789
790         return rrec;
791 }
792
793 /****************************************************************************
794  Queue a query name packet to a given address from the WINS subnet.
795 ****************************************************************************/
796
797 struct response_record *queue_query_name_from_wins_server( struct in_addr to_ip,
798                           response_function resp_fn,
799                           timeout_response_function timeout_fn,
800                           query_name_success_function success_fn,
801                           query_name_fail_function fail_fn,
802                           struct userdata_struct *userdata,
803                           struct nmb_name *nmbname)
804 {
805         struct packet_struct *p;
806         struct response_record *rrec;
807
808         if ((p = create_and_init_netbios_packet(nmbname, False, False, to_ip)) == NULL)
809                 return NULL;
810
811         if(initiate_name_query_packet_from_wins_server( p ) == False) {
812                 p->locked = False;
813                 free_packet(p);
814                 return NULL;
815         }
816
817         if((rrec = make_response_record(wins_server_subnet,            /* subnet record. */
818                                                 p,                     /* packet we sent. */
819                                                 resp_fn,               /* function to call on response. */
820                                                 timeout_fn,            /* function to call on timeout. */
821                                                 (success_function)success_fn,            /* function to call on operation success. */
822                                                 (fail_function)fail_fn,               /* function to call on operation fail. */
823                                                 userdata)) == NULL) {
824                 p->locked = False;
825                 free_packet(p);
826                 return NULL;
827         }
828
829         return rrec;
830 }
831
832 /****************************************************************************
833  Queue a node status packet to a given name and address.
834 ****************************************************************************/
835
836 struct response_record *queue_node_status( struct subnet_record *subrec,
837                           response_function resp_fn,
838                           timeout_response_function timeout_fn,
839                           node_status_success_function success_fn,
840                           node_status_fail_function fail_fn,
841                           struct userdata_struct *userdata,
842                           struct nmb_name *nmbname,
843                           struct in_addr send_ip)
844 {
845         struct packet_struct *p;
846         struct response_record *rrec;
847
848         /* Sanity check. */
849         if(subrec != unicast_subnet) {
850                 DEBUG(0,("queue_register_multihomed_name: should only be done on \
851 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
852                 return NULL;
853         }
854
855         if(assert_check_subnet(subrec))
856                 return NULL;
857
858         if(( p = create_and_init_netbios_packet(nmbname, False, False, send_ip)) == NULL)
859                 return NULL;
860
861         if(initiate_node_status_packet(p) == False) {
862                 p->locked = False;
863                 free_packet(p);
864                 return NULL;
865         }
866
867         if((rrec = make_response_record(subrec,           /* subnet record. */
868                                         p,                     /* packet we sent. */
869                                         resp_fn,               /* function to call on response. */
870                                         timeout_fn,            /* function to call on timeout. */
871                                         (success_function)success_fn,            /* function to call on operation success. */
872                                         (fail_function)fail_fn,               /* function to call on operation fail. */
873                                         userdata)) == NULL) {
874                 p->locked = False;
875                 free_packet(p);
876                 return NULL;
877         }
878
879         return rrec;
880 }
881
882 /****************************************************************************
883   Reply to a netbios name packet.  see rfc1002.txt
884 ****************************************************************************/
885
886 void reply_netbios_packet(struct packet_struct *orig_packet,
887                           int rcode, enum netbios_reply_type_code rcv_code, int opcode,
888                           int ttl, char *data,int len)
889 {
890         struct packet_struct packet;
891         struct nmb_packet *nmb = NULL;
892         struct res_rec answers;
893         struct nmb_packet *orig_nmb = &orig_packet->packet.nmb;
894         bool loopback_this_packet = False;
895         int rr_type = RR_TYPE_NB;
896         const char *packet_type = "unknown";
897
898         /* Check if we are sending to or from ourselves. */
899         if(ismyip_v4(orig_packet->ip) && (orig_packet->port == global_nmb_port))
900                 loopback_this_packet = True;
901
902         nmb = &packet.packet.nmb;
903
904         /* Do a partial copy of the packet. We clear the locked flag and
905                         the resource record pointers. */
906         packet = *orig_packet;   /* Full structure copy. */
907         packet.locked = False;
908         nmb->answers = NULL;
909         nmb->nsrecs = NULL;
910         nmb->additional = NULL;
911
912         switch (rcv_code) {
913                 case NMB_STATUS:
914                         packet_type = "nmb_status";
915                         nmb->header.nm_flags.recursion_desired = False;
916                         nmb->header.nm_flags.recursion_available = False;
917                         rr_type = RR_TYPE_NBSTAT;
918                         break;
919                 case NMB_QUERY:
920                         packet_type = "nmb_query";
921                         nmb->header.nm_flags.recursion_desired = True;
922                         nmb->header.nm_flags.recursion_available = True;
923                         if (rcode) {
924                                 rr_type = RR_TYPE_NULL;
925                         }
926                         break;
927                 case NMB_REG:
928                 case NMB_REG_REFRESH:
929                         packet_type = "nmb_reg";
930                         nmb->header.nm_flags.recursion_desired = True;
931                         nmb->header.nm_flags.recursion_available = True;
932                         break;
933                 case NMB_REL:
934                         packet_type = "nmb_rel";
935                         nmb->header.nm_flags.recursion_desired = False;
936                         nmb->header.nm_flags.recursion_available = False;
937                         break;
938                 case NMB_WAIT_ACK:
939                         packet_type = "nmb_wack";
940                         nmb->header.nm_flags.recursion_desired = False;
941                         nmb->header.nm_flags.recursion_available = False;
942                         rr_type = RR_TYPE_NULL;
943                         break;
944                 case WINS_REG:
945                         packet_type = "wins_reg";
946                         nmb->header.nm_flags.recursion_desired = True;
947                         nmb->header.nm_flags.recursion_available = True;
948                         break;
949                 case WINS_QUERY:
950                         packet_type = "wins_query";
951                         nmb->header.nm_flags.recursion_desired = True;
952                         nmb->header.nm_flags.recursion_available = True;
953                         if (rcode) {
954                                 rr_type = RR_TYPE_NULL;
955                         }
956                         break;
957                 default:
958                         DEBUG(0,("reply_netbios_packet: Unknown packet type: %s %s to ip %s\n",
959                                 packet_type, nmb_namestr(&orig_nmb->question.question_name),
960                                 inet_ntoa(packet.ip)));
961                         return;
962         }
963
964         DEBUG(4,("reply_netbios_packet: sending a reply of packet type: %s %s to ip %s \
965 for id %hu\n", packet_type, nmb_namestr(&orig_nmb->question.question_name),
966                         inet_ntoa(packet.ip), orig_nmb->header.name_trn_id));
967
968         nmb->header.name_trn_id = orig_nmb->header.name_trn_id;
969         nmb->header.opcode = opcode;
970         nmb->header.response = True;
971         nmb->header.nm_flags.bcast = False;
972         nmb->header.nm_flags.trunc = False;
973         nmb->header.nm_flags.authoritative = True;
974
975         nmb->header.rcode = rcode;
976         nmb->header.qdcount = 0;
977         nmb->header.ancount = 1;
978         nmb->header.nscount = 0;
979         nmb->header.arcount = 0;
980
981         memset((char*)&nmb->question,'\0',sizeof(nmb->question));
982
983         nmb->answers = &answers;
984         memset((char*)nmb->answers,'\0',sizeof(*nmb->answers));
985
986         nmb->answers->rr_name  = orig_nmb->question.question_name;
987         nmb->answers->rr_type  = rr_type;
988         nmb->answers->rr_class = RR_CLASS_IN;
989         nmb->answers->ttl      = ttl;
990
991         if (data && len) {
992                 if (len < 0 || len > sizeof(nmb->answers->rdata)) {
993                         DEBUG(5,("reply_netbios_packet: "
994                                 "invalid packet len (%d)\n",
995                                 len ));
996                         return;
997                 }
998                 nmb->answers->rdlength = len;
999                 memcpy(nmb->answers->rdata, data, len);
1000         }
1001
1002         packet.packet_type = NMB_PACKET;
1003         packet.recv_fd = -1;
1004         /* Ensure we send out on the same fd that the original
1005                 packet came in on to give the correct source IP address. */
1006         if (orig_packet->send_fd != -1) {
1007                 packet.send_fd = orig_packet->send_fd;
1008         } else {
1009                 packet.send_fd = orig_packet->recv_fd;
1010         }
1011         packet.timestamp = time(NULL);
1012
1013         debug_nmb_packet(&packet);
1014
1015         if(loopback_this_packet) {
1016                 struct packet_struct *lo_packet;
1017                 DEBUG(5,("reply_netbios_packet: sending packet to ourselves.\n"));
1018                 if((lo_packet = copy_packet(&packet)) == NULL)
1019                         return;
1020                 queue_packet(lo_packet);
1021         } else if (!send_packet(&packet)) {
1022                 DEBUG(0,("reply_netbios_packet: send_packet to IP %s port %d failed\n",
1023                         inet_ntoa(packet.ip),packet.port));
1024         }
1025 }
1026
1027 /*******************************************************************
1028   Queue a packet into a packet queue
1029 ******************************************************************/
1030
1031 void queue_packet(struct packet_struct *packet)
1032 {
1033         DLIST_ADD_END(packet_queue, packet, struct packet_struct *);
1034 }
1035
1036 /****************************************************************************
1037  Try and find a matching subnet record for a datagram port 138 packet.
1038 ****************************************************************************/
1039
1040 static struct subnet_record *find_subnet_for_dgram_browse_packet(struct packet_struct *p)
1041 {
1042         struct subnet_record *subrec;
1043
1044         /* Go through all the broadcast subnets and see if the mask matches. */
1045         for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1046                 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1047                         return subrec;
1048         }
1049
1050         /* If the subnet record is the remote announce broadcast subnet,
1051                 hack it here to be the first subnet. This is really gross and
1052                 is needed due to people turning on port 137/138 broadcast
1053                 forwarding on their routers. May fire and brimstone rain
1054                 down upon them...
1055         */
1056
1057         return FIRST_SUBNET;
1058 }
1059
1060 /****************************************************************************
1061 Dispatch a browse frame from port 138 to the correct processing function.
1062 ****************************************************************************/
1063
1064 static void process_browse_packet(struct packet_struct *p, char *buf,int len)
1065 {
1066         struct dgram_packet *dgram = &p->packet.dgram;
1067         int command = CVAL(buf,0);
1068         struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1069         char scope[64];
1070         unstring src_name;
1071
1072         /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1073         pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1074         if (!strequal(scope, global_scope())) {
1075                 DEBUG(7,("process_browse_packet: Discarding datagram from IP %s. Scope (%s) \
1076 mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
1077                 return;
1078         }
1079
1080         pull_ascii_nstring(src_name, sizeof(src_name), dgram->source_name.name);
1081         if (is_myname(src_name)) {
1082                 DEBUG(7,("process_browse_packet: Discarding datagram from IP %s. Source name \
1083 %s is one of our names !\n", inet_ntoa(p->ip), nmb_namestr(&dgram->source_name)));
1084                 return;
1085         }
1086
1087         switch (command) {
1088                 case ANN_HostAnnouncement:
1089                         debug_browse_data(buf, len);
1090                         process_host_announce(subrec, p, buf+1);
1091                         break;
1092                 case ANN_DomainAnnouncement:
1093                         debug_browse_data(buf, len);
1094                         process_workgroup_announce(subrec, p, buf+1);
1095                         break;
1096                 case ANN_LocalMasterAnnouncement:
1097                         debug_browse_data(buf, len);
1098                         process_local_master_announce(subrec, p, buf+1);
1099                         break;
1100                 case ANN_AnnouncementRequest:
1101                         debug_browse_data(buf, len);
1102                         process_announce_request(subrec, p, buf+1);
1103                         break;
1104                 case ANN_Election:
1105                         debug_browse_data(buf, len);
1106                         process_election(subrec, p, buf+1);
1107                         break;
1108                 case ANN_GetBackupListReq:
1109                         debug_browse_data(buf, len);
1110                         process_get_backup_list_request(subrec, p, buf+1);
1111                         break;
1112                 case ANN_GetBackupListResp:
1113                         debug_browse_data(buf, len);
1114                         /* We never send ANN_GetBackupListReq so we should never get these. */
1115                         DEBUG(0,("process_browse_packet: Discarding GetBackupListResponse \
1116 packet from %s IP %s\n", nmb_namestr(&dgram->source_name), inet_ntoa(p->ip)));
1117                         break;
1118                 case ANN_ResetBrowserState:
1119                         debug_browse_data(buf, len);
1120                         process_reset_browser(subrec, p, buf+1);
1121                         break;
1122                 case ANN_MasterAnnouncement:
1123                         /* Master browser datagrams must be processed on the unicast subnet. */
1124                         subrec = unicast_subnet;
1125
1126                         debug_browse_data(buf, len);
1127                         process_master_browser_announce(subrec, p, buf+1);
1128                         break;
1129                 case ANN_BecomeBackup:
1130                         /*
1131                          * We don't currently implement this. Log it just in case.
1132                          */
1133                         debug_browse_data(buf, len);
1134                         DEBUG(10,("process_browse_packet: On subnet %s ignoring browse packet \
1135 command ANN_BecomeBackup from %s IP %s to %s\n", subrec->subnet_name, nmb_namestr(&dgram->source_name),
1136                                         inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1137                         break;
1138                 default:
1139                         debug_browse_data(buf, len);
1140                         DEBUG(0,("process_browse_packet: On subnet %s ignoring browse packet \
1141 command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namestr(&dgram->source_name),
1142                                 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1143                         break;
1144         }
1145 }
1146
1147 /****************************************************************************
1148  Dispatch a LanMan browse frame from port 138 to the correct processing function.
1149 ****************************************************************************/
1150
1151 static void process_lanman_packet(struct packet_struct *p, char *buf,int len)
1152 {
1153         struct dgram_packet *dgram = &p->packet.dgram;
1154         int command = SVAL(buf,0);
1155         struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1156         char scope[64];
1157         unstring src_name;
1158
1159         /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1160
1161         pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1162         if (!strequal(scope, global_scope())) {
1163                 DEBUG(7,("process_lanman_packet: Discarding datagram from IP %s. Scope (%s) \
1164 mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
1165                 return;
1166         }
1167
1168         pull_ascii_nstring(src_name, sizeof(src_name), dgram->source_name.name);
1169         if (is_myname(src_name)) {
1170                 DEBUG(0,("process_lanman_packet: Discarding datagram from IP %s. Source name \
1171 %s is one of our names !\n", inet_ntoa(p->ip), nmb_namestr(&dgram->source_name)));
1172                 return;
1173         }
1174
1175         switch (command) {
1176                 case ANN_HostAnnouncement:
1177                         debug_browse_data(buf, len);
1178                         process_lm_host_announce(subrec, p, buf+1, len > 1 ? len-1 : 0);
1179                         break;
1180                 case ANN_AnnouncementRequest:
1181                         process_lm_announce_request(subrec, p, buf+1, len > 1 ? len-1 : 0);
1182                         break;
1183                 default:
1184                         DEBUG(0,("process_lanman_packet: On subnet %s ignoring browse packet \
1185 command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namestr(&dgram->source_name),
1186                                 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1187                         break;
1188         }
1189 }
1190
1191 /****************************************************************************
1192   Determine if a packet is for us on port 138. Note that to have any chance of
1193   being efficient we need to drop as many packets as possible at this
1194   stage as subsequent processing is expensive. 
1195 ****************************************************************************/
1196
1197 static bool listening(struct packet_struct *p,struct nmb_name *nbname)
1198 {
1199         struct subnet_record *subrec = NULL;
1200
1201         for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1202                 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1203                         break;
1204         }
1205
1206         if(subrec == NULL)
1207                 subrec = unicast_subnet;
1208
1209         return (find_name_on_subnet(subrec, nbname, FIND_SELF_NAME) != NULL);
1210 }
1211
1212 /****************************************************************************
1213   Process udp 138 datagrams
1214 ****************************************************************************/
1215
1216 static void process_dgram(struct packet_struct *p)
1217 {
1218         char *buf;
1219         char *buf2;
1220         int len;
1221         struct dgram_packet *dgram = &p->packet.dgram;
1222
1223         /* If we aren't listening to the destination name then ignore the packet */
1224         if (!listening(p,&dgram->dest_name)) {
1225                         nb_packet_dispatch(packet_server, p);
1226                         DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from %s\n",
1227                                 nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip)));
1228                         return;
1229         }
1230
1231         if (dgram->header.msg_type != 0x10 && dgram->header.msg_type != 0x11 && dgram->header.msg_type != 0x12) {
1232                 nb_packet_dispatch(packet_server, p);
1233                 /* Don't process error packets etc yet */
1234                 DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from IP %s as it is \
1235 an error packet of type %x\n", nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip), dgram->header.msg_type));
1236                 return;
1237         }
1238
1239         /* Ensure we have a large enough packet before looking inside. */
1240         if (dgram->datasize < (smb_vwv12 - 2)) {
1241                 /* That's the offset minus the 4 byte length + 2 bytes of offset. */
1242                 DEBUG(0,("process_dgram: ignoring too short dgram packet (%u) sent to name %s from IP %s\n",
1243                         (unsigned int)dgram->datasize,
1244                         nmb_namestr(&dgram->dest_name),
1245                         inet_ntoa(p->ip) ));
1246                 return;
1247         }
1248
1249         buf = &dgram->data[0];
1250         buf -= 4; /* XXXX for the pseudo tcp length - someday I need to get rid of this */
1251
1252         if (CVAL(buf,smb_com) != SMBtrans)
1253                 return;
1254
1255         len = SVAL(buf,smb_vwv11);
1256         buf2 = smb_base(buf) + SVAL(buf,smb_vwv12);
1257
1258         if (len <= 0 || len > dgram->datasize) {
1259                 DEBUG(0,("process_dgram: ignoring malformed1 (datasize = %d, len = %d) datagram \
1260 packet sent to name %s from IP %s\n",
1261                         dgram->datasize,
1262                         len,
1263                         nmb_namestr(&dgram->dest_name),
1264                         inet_ntoa(p->ip) ));
1265                 return;
1266         }
1267
1268         if (buf2 < dgram->data || (buf2 >= dgram->data + dgram->datasize)) {
1269                 DEBUG(0,("process_dgram: ignoring malformed2 (datasize = %d, len=%d, off=%d) datagram \
1270 packet sent to name %s from IP %s\n",
1271                         dgram->datasize,
1272                         len,
1273                         (int)PTR_DIFF(buf2, dgram->data),
1274                         nmb_namestr(&dgram->dest_name),
1275                         inet_ntoa(p->ip) ));
1276                 return;
1277         }
1278
1279         if ((buf2 + len < dgram->data) || (buf2 + len > dgram->data + dgram->datasize)) {
1280                 DEBUG(0,("process_dgram: ignoring malformed3 (datasize = %d, len=%d, off=%d) datagram \
1281 packet sent to name %s from IP %s\n",
1282                         dgram->datasize,
1283                         len,
1284                         (int)PTR_DIFF(buf2, dgram->data),
1285                         nmb_namestr(&dgram->dest_name),
1286                         inet_ntoa(p->ip) ));
1287                 return;
1288         }
1289
1290         DEBUG(4,("process_dgram: datagram from %s to %s IP %s for %s of type %d len=%d\n",
1291                 nmb_namestr(&dgram->source_name),nmb_namestr(&dgram->dest_name),
1292                 inet_ntoa(p->ip), smb_buf(buf),CVAL(buf2,0),len));
1293
1294         /* Datagram packet received for the browser mailslot */
1295         if (strequal(smb_buf(buf),BROWSE_MAILSLOT)) {
1296                 process_browse_packet(p,buf2,len);
1297                 return;
1298         }
1299
1300         /* Datagram packet received for the LAN Manager mailslot */
1301         if (strequal(smb_buf(buf),LANMAN_MAILSLOT)) {
1302                 process_lanman_packet(p,buf2,len);
1303                 return;
1304         }
1305
1306         /* Datagram packet received for the domain logon mailslot */
1307         if (strequal(smb_buf(buf),NET_LOGON_MAILSLOT)) {
1308                 process_logon_packet(p,buf2,len,NET_LOGON_MAILSLOT);
1309                 return;
1310         }
1311
1312         /* Datagram packet received for the NT domain logon mailslot */
1313         if (strequal(smb_buf(buf),NT_LOGON_MAILSLOT)) {
1314                 process_logon_packet(p,buf2,len,NT_LOGON_MAILSLOT);
1315                 return;
1316         }
1317
1318         nb_packet_dispatch(packet_server, p);
1319 }
1320
1321 /****************************************************************************
1322   Validate a response nmb packet.
1323 ****************************************************************************/
1324
1325 static bool validate_nmb_response_packet( struct nmb_packet *nmb )
1326 {
1327         bool ignore = False;
1328
1329         switch (nmb->header.opcode) {
1330                 case NMB_NAME_REG_OPCODE:
1331                 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1332                 case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1333                         if (nmb->header.ancount == 0) {
1334                                 DEBUG(0,("validate_nmb_response_packet: Bad REG/REFRESH Packet. "));
1335                                 ignore = True;
1336                         }
1337                         break;
1338
1339                 case NMB_NAME_QUERY_OPCODE:
1340                         if ((nmb->header.ancount != 0) && (nmb->header.ancount != 1)) {
1341                                 DEBUG(0,("validate_nmb_response_packet: Bad QUERY Packet. "));
1342                                 ignore = True;
1343                         }
1344                         break;
1345
1346                 case NMB_NAME_RELEASE_OPCODE:
1347                         if (nmb->header.ancount == 0) {
1348                                 DEBUG(0,("validate_nmb_response_packet: Bad RELEASE Packet. "));
1349                                 ignore = True;
1350                         }
1351                         break;
1352
1353                 case NMB_WACK_OPCODE:
1354                         /* Check WACK response here. */
1355                         if (nmb->header.ancount != 1) {
1356                                 DEBUG(0,("validate_nmb_response_packet: Bad WACK Packet. "));
1357                                 ignore = True;
1358                         }
1359                         break;
1360                 default:
1361                         DEBUG(0,("validate_nmb_response_packet: Ignoring packet with unknown opcode %d.\n",
1362                                         nmb->header.opcode));
1363                         return True;
1364         }
1365
1366         if(ignore)
1367                 DEBUG(0,("Ignoring response packet with opcode %d.\n", nmb->header.opcode));
1368
1369         return ignore;
1370 }
1371
1372 /****************************************************************************
1373   Validate a request nmb packet.
1374 ****************************************************************************/
1375
1376 static bool validate_nmb_packet( struct nmb_packet *nmb )
1377 {
1378         bool ignore = False;
1379
1380         switch (nmb->header.opcode) {
1381                 case NMB_NAME_REG_OPCODE:
1382                 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1383                 case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1384                 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1385                         if (nmb->header.qdcount==0 || nmb->header.arcount==0) {
1386                                 DEBUG(0,("validate_nmb_packet: Bad REG/REFRESH Packet. "));
1387                                 ignore = True;
1388                         }
1389                         break;
1390
1391                 case NMB_NAME_QUERY_OPCODE:
1392                         if ((nmb->header.qdcount == 0) || ((nmb->question.question_type != QUESTION_TYPE_NB_QUERY) &&
1393                                         (nmb->question.question_type != QUESTION_TYPE_NB_STATUS))) {
1394                                 DEBUG(0,("validate_nmb_packet: Bad QUERY Packet. "));
1395                                 ignore = True;
1396                         }
1397                         break;
1398
1399                 case NMB_NAME_RELEASE_OPCODE:
1400                         if (nmb->header.qdcount==0 || nmb->header.arcount==0) {
1401                                 DEBUG(0,("validate_nmb_packet: Bad RELEASE Packet. "));
1402                                 ignore = True;
1403                         }
1404                         break;
1405                 default:
1406                         DEBUG(0,("validate_nmb_packet: Ignoring packet with unknown opcode %d.\n",
1407                                 nmb->header.opcode));
1408                         return True;
1409         }
1410
1411         if(ignore)
1412                 DEBUG(0,("validate_nmb_packet: Ignoring request packet with opcode %d.\n", nmb->header.opcode));
1413
1414         return ignore;
1415 }
1416
1417 /****************************************************************************
1418   Find a subnet (and potentially a response record) for a packet.
1419 ****************************************************************************/
1420
1421 static struct subnet_record *find_subnet_for_nmb_packet( struct packet_struct *p,
1422                                                          struct response_record **pprrec)
1423 {
1424         struct nmb_packet *nmb = &p->packet.nmb;
1425         struct response_record *rrec = NULL;
1426         struct subnet_record *subrec = NULL;
1427
1428         if(pprrec != NULL)
1429                 *pprrec = NULL;
1430
1431         if(nmb->header.response) {
1432                 /* It's a response packet. Find a record for it or it's an error. */
1433
1434                 rrec = find_response_record( &subrec, nmb->header.name_trn_id);
1435                 if(rrec == NULL) {
1436                         DEBUG(3,("find_subnet_for_nmb_packet: response record not found for response id %hu\n",
1437                                 nmb->header.name_trn_id));
1438                         nb_packet_dispatch(packet_server, p);
1439                         return NULL;
1440                 }
1441
1442                 if(subrec == NULL) {
1443                         DEBUG(0,("find_subnet_for_nmb_packet: subnet record not found for response id %hu\n",
1444                                 nmb->header.name_trn_id));
1445                         return NULL;
1446                 }
1447
1448                 if(pprrec != NULL)
1449                         *pprrec = rrec;
1450                 return subrec;
1451         }
1452
1453         /* Try and see what subnet this packet belongs to. */
1454
1455         /* WINS server ? */
1456         if(packet_is_for_wins_server(p))
1457                 return wins_server_subnet;
1458
1459         /* If it wasn't a broadcast packet then send to the UNICAST subnet. */
1460         if(nmb->header.nm_flags.bcast == False)
1461                 return unicast_subnet;
1462
1463         /* Go through all the broadcast subnets and see if the mask matches. */
1464         for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1465                 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1466                         return subrec;
1467         }
1468
1469         /* If none match it must have been a directed broadcast - assign the remote_broadcast_subnet. */
1470         return remote_broadcast_subnet;
1471 }
1472
1473 /****************************************************************************
1474   Process a nmb request packet - validate the packet and route it.
1475 ****************************************************************************/
1476
1477 static void process_nmb_request(struct packet_struct *p)
1478 {
1479         struct nmb_packet *nmb = &p->packet.nmb;
1480         struct subnet_record *subrec = NULL;
1481
1482         debug_nmb_packet(p);
1483
1484         /* Ensure we have a good packet. */
1485         if(validate_nmb_packet(nmb))
1486                 return;
1487
1488         /* Allocate a subnet to this packet - if we cannot - fail. */
1489         if((subrec = find_subnet_for_nmb_packet(p, NULL))==NULL)
1490                 return;
1491
1492         switch (nmb->header.opcode) {
1493                 case NMB_NAME_REG_OPCODE:
1494                         if(subrec == wins_server_subnet)
1495                                 wins_process_name_registration_request(subrec, p);
1496                         else
1497                                 process_name_registration_request(subrec, p);
1498                         break;
1499
1500                 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1501                 case NMB_NAME_REFRESH_OPCODE_9:
1502                         if(subrec == wins_server_subnet)
1503                                 wins_process_name_refresh_request(subrec, p);
1504                         else
1505                                 process_name_refresh_request(subrec, p);
1506                         break;
1507
1508                 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1509                         if(subrec == wins_server_subnet) {
1510                                 wins_process_multihomed_name_registration_request(subrec, p);
1511                         } else {
1512                                 DEBUG(0,("process_nmb_request: Multihomed registration request must be \
1513 directed at a WINS server.\n"));
1514                         }
1515                         break;
1516
1517                 case NMB_NAME_QUERY_OPCODE:
1518                         switch (nmb->question.question_type) {
1519                                 case QUESTION_TYPE_NB_QUERY:
1520                                         if(subrec == wins_server_subnet)
1521                                                 wins_process_name_query_request(subrec, p);
1522                                         else
1523                                                 process_name_query_request(subrec, p);
1524                                         break;
1525                                 case QUESTION_TYPE_NB_STATUS:
1526                                         if(subrec == wins_server_subnet) {
1527                                                 DEBUG(0,("process_nmb_request: NB_STATUS request directed at WINS server is \
1528 not allowed.\n"));
1529                                                 break;
1530                                         } else {
1531                                                 process_node_status_request(subrec, p);
1532                                         }
1533                                         break;
1534                         }
1535                         break;
1536
1537                 case NMB_NAME_RELEASE_OPCODE:
1538                         if(subrec == wins_server_subnet)
1539                                 wins_process_name_release_request(subrec, p);
1540                         else
1541                                 process_name_release_request(subrec, p);
1542                         break;
1543         }
1544 }
1545
1546 /****************************************************************************
1547   Process a nmb response packet - validate the packet and route it.
1548   to either the WINS server or a normal response.
1549 ****************************************************************************/
1550
1551 static void process_nmb_response(struct packet_struct *p)
1552 {
1553         struct nmb_packet *nmb = &p->packet.nmb;
1554         struct subnet_record *subrec = NULL;
1555         struct response_record *rrec = NULL;
1556
1557         debug_nmb_packet(p);
1558
1559         if(validate_nmb_response_packet(nmb))
1560                 return;
1561
1562         if((subrec = find_subnet_for_nmb_packet(p, &rrec))==NULL)
1563                 return;
1564
1565         if(rrec == NULL) {
1566                 DEBUG(0,("process_nmb_response: response packet received but no response record \
1567 found for id = %hu. Ignoring packet.\n", nmb->header.name_trn_id));
1568                 return;
1569         }
1570
1571         /* Increment the number of responses received for this record. */
1572         rrec->num_msgs++;
1573         /* Ensure we don't re-send the request. */
1574         rrec->repeat_count = 0;
1575
1576         /* Call the response received function for this packet. */
1577         (*rrec->resp_fn)(subrec, rrec, p);
1578 }
1579
1580 /*******************************************************************
1581   Run elements off the packet queue till its empty
1582 ******************************************************************/
1583
1584 void run_packet_queue(void)
1585 {
1586         struct packet_struct *p;
1587
1588         while ((p = packet_queue)) {
1589                 DLIST_REMOVE(packet_queue, p);
1590
1591                 switch (p->packet_type) {
1592                         case NMB_PACKET:
1593                                 if(p->packet.nmb.header.response)
1594                                         process_nmb_response(p);
1595                                 else
1596                                         process_nmb_request(p);
1597                                 break;
1598
1599                         case DGRAM_PACKET:
1600                                 process_dgram(p);
1601                                 break;
1602                 }
1603                 free_packet(p);
1604         }
1605 }
1606
1607 /*******************************************************************
1608  Retransmit or timeout elements from all the outgoing subnet response
1609  record queues. NOTE that this code must also check the WINS server
1610  subnet for response records to timeout as the WINS server code
1611  can send requests to check if a client still owns a name.
1612  (Patch from Andrey Alekseyev <fetch@muffin.arcadia.spb.ru>).
1613 ******************************************************************/
1614
1615 void retransmit_or_expire_response_records(time_t t)
1616 {
1617         struct subnet_record *subrec;
1618
1619         for (subrec = FIRST_SUBNET; subrec; subrec = get_next_subnet_maybe_unicast_or_wins_server(subrec)) {
1620                 struct response_record *rrec, *nextrrec;
1621
1622   restart:
1623
1624                 for (rrec = subrec->responselist; rrec; rrec = nextrrec) {
1625                         nextrrec = rrec->next;
1626
1627                         if (rrec->repeat_time <= t) {
1628                                 if (rrec->repeat_count > 0) {
1629                                         /* Resend while we have a non-zero repeat_count. */
1630                                         if(!send_packet(rrec->packet)) {
1631                                                 DEBUG(0,("retransmit_or_expire_response_records: Failed to resend packet id %hu \
1632 to IP %s on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1633                                         }
1634                                         rrec->repeat_time = t + rrec->repeat_interval;
1635                                         rrec->repeat_count--;
1636                                 } else {
1637                                         DEBUG(4,("retransmit_or_expire_response_records: timeout for packet id %hu to IP %s \
1638 on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1639
1640                                         /*
1641                                          * Check the flag in this record to prevent recursion if we end
1642                                          * up in this function again via the timeout function call.
1643                                          */
1644
1645                                         if(!rrec->in_expiration_processing) {
1646
1647                                                 /*
1648                                                  * Set the recursion protection flag in this record.
1649                                                  */
1650
1651                                                 rrec->in_expiration_processing = True;
1652
1653                                                 /* Call the timeout function. This will deal with removing the
1654                                                                 timed out packet. */
1655                                                 if(rrec->timeout_fn) {
1656                                                         (*rrec->timeout_fn)(subrec, rrec);
1657                                                 } else {
1658                                                         /* We must remove the record ourself if there is
1659                                                                         no timeout function. */
1660                                                         remove_response_record(subrec, rrec);
1661                                                 }
1662                                                 /* We have changed subrec->responselist,
1663                                                  * restart from the beginning of this list. */
1664                                                 goto restart;
1665                                         } /* !rrec->in_expitation_processing */
1666                                 } /* rrec->repeat_count > 0 */
1667                         } /* rrec->repeat_time <= t */
1668                 } /* end for rrec */
1669         } /* end for subnet */
1670 }
1671
1672 /****************************************************************************
1673   Create an fd_set containing all the sockets in the subnet structures,
1674   plus the broadcast sockets.
1675 ***************************************************************************/
1676
1677 static bool create_listen_fdset(fd_set **ppset, int **psock_array, int *listen_number, int *maxfd)
1678 {
1679         int *sock_array = NULL;
1680         struct subnet_record *subrec = NULL;
1681         int count = 0;
1682         int num = 0;
1683         fd_set *pset = SMB_MALLOC_P(fd_set);
1684
1685         if(pset == NULL) {
1686                 DEBUG(0,("create_listen_fdset: malloc fail !\n"));
1687                 return True;
1688         }
1689
1690         /* The Client* sockets */
1691         count++;
1692
1693         /* Check that we can add all the fd's we need. */
1694         for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1695                 count++;
1696
1697         /* each interface gets 4 sockets */
1698         count *= 4;
1699
1700         if(count > FD_SETSIZE) {
1701                 DEBUG(0,("create_listen_fdset: Too many file descriptors needed (%d). We can \
1702 only use %d.\n", count, FD_SETSIZE));
1703                 SAFE_FREE(pset);
1704                 return True;
1705         }
1706
1707         if((sock_array = SMB_MALLOC_ARRAY(int, count)) == NULL) {
1708                 DEBUG(0,("create_listen_fdset: malloc fail for socket array. size %d\n", count));
1709                 SAFE_FREE(pset);
1710                 return True;
1711         }
1712
1713         FD_ZERO(pset);
1714
1715         /* Add in the lp_socket_address() interface on 137. */
1716         FD_SET(ClientNMB,pset);
1717         sock_array[num++] = ClientNMB;
1718         *maxfd = MAX( *maxfd, ClientNMB);
1719
1720         /* the lp_socket_address() interface has only one socket */
1721         sock_array[num++] = -1;
1722
1723         /* Add in the 137 sockets on all the interfaces. */
1724         for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1725                 FD_SET(subrec->nmb_sock,pset);
1726                 sock_array[num++] = subrec->nmb_sock;
1727                 *maxfd = MAX( *maxfd, subrec->nmb_sock);
1728
1729                 sock_array[num++] = subrec->nmb_bcast;
1730                 if (subrec->nmb_bcast != -1) {
1731                         FD_SET(subrec->nmb_bcast,pset);
1732                         *maxfd = MAX( *maxfd, subrec->nmb_bcast);
1733                 }
1734         }
1735
1736         /* Add in the lp_socket_address() interface on 138. */
1737         FD_SET(ClientDGRAM,pset);
1738         sock_array[num++] = ClientDGRAM;
1739         *maxfd = MAX( *maxfd, ClientDGRAM);
1740
1741         /* the lp_socket_address() interface has only one socket */
1742         sock_array[num++] = -1;
1743
1744         /* Add in the 138 sockets on all the interfaces. */
1745         for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1746                 FD_SET(subrec->dgram_sock,pset);
1747                 sock_array[num++] = subrec->dgram_sock;
1748                 *maxfd = MAX( *maxfd, subrec->dgram_sock);
1749
1750                 sock_array[num++] = subrec->dgram_bcast;
1751                 if (subrec->dgram_bcast != -1) {
1752                         FD_SET(subrec->dgram_bcast,pset);
1753                         *maxfd = MAX( *maxfd, subrec->dgram_bcast);
1754                 }
1755         }
1756
1757         *listen_number = count;
1758
1759         SAFE_FREE(*ppset);
1760         SAFE_FREE(*psock_array);
1761
1762         *ppset = pset;
1763         *psock_array = sock_array;
1764
1765         return False;
1766 }
1767
1768 /****************************************************************************
1769  List of packets we're processing this select.
1770 ***************************************************************************/
1771
1772 struct processed_packet {
1773         struct processed_packet *next;
1774         struct processed_packet *prev;
1775         enum packet_type packet_type;
1776         struct in_addr ip;
1777         int packet_id;
1778 };
1779
1780 /****************************************************************************
1781  Have we seen this before ?
1782 ***************************************************************************/
1783
1784 static bool is_processed_packet(struct processed_packet *processed_packet_list,
1785                                 struct packet_struct *packet)
1786 {
1787         struct processed_packet *p = NULL;
1788
1789         for (p = processed_packet_list; p; p = p->next) {
1790                 if (ip_equal_v4(p->ip, packet->ip) && p->packet_type == packet->packet_type) {
1791                         if ((p->packet_type == NMB_PACKET) &&
1792                                 (p->packet_id ==
1793                                         packet->packet.nmb.header.name_trn_id)) {
1794                                 return true;
1795                         } else if ((p->packet_type == DGRAM_PACKET) &&
1796                                 (p->packet_id ==
1797                                         packet->packet.dgram.header.dgm_id)) {
1798                                 return true;
1799                         }
1800                 }
1801         }
1802         return false;
1803 }
1804
1805 /****************************************************************************
1806  Keep a list of what we've seen before.
1807 ***************************************************************************/
1808
1809 static bool store_processed_packet(struct processed_packet **pp_processed_packet_list,
1810                                 struct packet_struct *packet)
1811 {
1812         struct processed_packet *p = SMB_MALLOC_P(struct processed_packet);
1813         if (!p) {
1814                 return false;
1815         }
1816         p->packet_type = packet->packet_type;
1817         p->ip = packet->ip;
1818         if (packet->packet_type == NMB_PACKET) {
1819                 p->packet_id = packet->packet.nmb.header.name_trn_id;
1820         } else if (packet->packet_type == DGRAM_PACKET) {
1821                 p->packet_id = packet->packet.dgram.header.dgm_id;
1822         } else {
1823                 return false;
1824         }
1825
1826         DLIST_ADD(*pp_processed_packet_list, p);
1827         return true;
1828 }
1829
1830 /****************************************************************************
1831  Throw away what we've seen before.
1832 ***************************************************************************/
1833
1834 static void free_processed_packet_list(struct processed_packet **pp_processed_packet_list)
1835 {
1836         struct processed_packet *p = NULL, *next = NULL;
1837
1838         for (p = *pp_processed_packet_list; p; p = next) {
1839                 next = p->next;
1840                 DLIST_REMOVE(*pp_processed_packet_list, p);
1841                 SAFE_FREE(p);
1842         }
1843 }
1844
1845 /****************************************************************************
1846   Listens for NMB or DGRAM packets, and queues them.
1847   return True if the socket is dead
1848 ***************************************************************************/
1849
1850 bool listen_for_packets(bool run_election)
1851 {
1852         static fd_set *listen_set = NULL;
1853         static int listen_number = 0;
1854         static int *sock_array = NULL;
1855         int i;
1856         static int maxfd = 0;
1857
1858         fd_set r_fds;
1859         fd_set w_fds;
1860         int selrtn;
1861         struct timeval timeout;
1862 #ifndef SYNC_DNS
1863         int dns_fd;
1864 #endif
1865         struct processed_packet *processed_packet_list = NULL;
1866
1867         if(listen_set == NULL || rescan_listen_set) {
1868                 if(create_listen_fdset(&listen_set, &sock_array, &listen_number, &maxfd)) {
1869                         DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
1870                         return True;
1871                 }
1872                 rescan_listen_set = False;
1873         }
1874
1875         memcpy((char *)&r_fds, (char *)listen_set, sizeof(fd_set));
1876         FD_ZERO(&w_fds);
1877
1878 #ifndef SYNC_DNS
1879         dns_fd = asyncdns_fd();
1880         if (dns_fd != -1) {
1881                 FD_SET(dns_fd, &r_fds);
1882                 maxfd = MAX( maxfd, dns_fd);
1883         }
1884 #endif
1885
1886         /* Process a signal and timer events now... */
1887         if (run_events(nmbd_event_context(), 0, NULL, NULL)) {
1888                 return False;
1889         }
1890
1891         /*
1892          * During elections and when expecting a netbios response packet we
1893          * need to send election packets at tighter intervals.
1894          * Ideally it needs to be the interval (in ms) between time now and
1895          * the time we are expecting the next netbios packet.
1896          */
1897
1898         timeout.tv_sec = (run_election||num_response_packets) ? 1 : NMBD_SELECT_LOOP;
1899         timeout.tv_usec = 0;
1900
1901         event_add_to_select_args(nmbd_event_context(),
1902                                  &r_fds, &w_fds, &timeout, &maxfd);
1903
1904         selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&timeout);
1905
1906         if (run_events(nmbd_event_context(), selrtn, &r_fds, &w_fds)) {
1907                 return False;
1908         }
1909
1910         if (selrtn == -1) {
1911                 return False;
1912         }
1913
1914 #ifndef SYNC_DNS
1915         if (dns_fd != -1 && FD_ISSET(dns_fd,&r_fds)) {
1916                 run_dns_queue();
1917         }
1918 #endif
1919
1920         for(i = 0; i < listen_number; i++) {
1921                 enum packet_type packet_type;
1922                 struct packet_struct *packet;
1923                 const char *packet_name;
1924                 int client_fd;
1925                 int client_port;
1926
1927                 if (sock_array[i] == -1) {
1928                         continue;
1929                 }
1930
1931                 if (!FD_ISSET(sock_array[i],&r_fds)) {
1932                         continue;
1933                 }
1934
1935                 if (i < (listen_number/2)) {
1936                         /* Port 137 */
1937                         packet_type = NMB_PACKET;
1938                         packet_name = "nmb";
1939                         client_fd = ClientNMB;
1940                         client_port = global_nmb_port;
1941                 } else {
1942                         /* Port 138 */
1943                         packet_type = DGRAM_PACKET;
1944                         packet_name = "dgram";
1945                         client_fd = ClientDGRAM;
1946                         client_port = DGRAM_PORT;
1947                 }
1948
1949                 packet = read_packet(sock_array[i], packet_type);
1950                 if (!packet) {
1951                         continue;
1952                 }
1953
1954                 /*
1955                  * If we got a packet on the broadcast socket and interfaces
1956                  * only is set then check it came from one of our local nets.
1957                  */
1958                 if (lp_bind_interfaces_only() &&
1959                     (sock_array[i] == client_fd) &&
1960                     (!is_local_net_v4(packet->ip))) {
1961                         DEBUG(7,("discarding %s packet sent to broadcast socket from %s:%d\n",
1962                                 packet_name, inet_ntoa(packet->ip), packet->port));
1963                         free_packet(packet);
1964                         continue;
1965                 }
1966
1967                 if ((is_loopback_ip_v4(packet->ip) || ismyip_v4(packet->ip)) &&
1968                     packet->port == client_port)
1969                 {
1970                         if (client_port == DGRAM_PORT) {
1971                                 DEBUG(7,("discarding own dgram packet from %s:%d\n",
1972                                         inet_ntoa(packet->ip),packet->port));
1973                                 free_packet(packet);
1974                                 continue;
1975                         }
1976
1977                         if (packet->packet.nmb.header.nm_flags.bcast) {
1978                                 DEBUG(7,("discarding own nmb bcast packet from %s:%d\n",
1979                                         inet_ntoa(packet->ip),packet->port));
1980                                 free_packet(packet);
1981                                 continue;
1982                         }
1983                 }
1984
1985                 if (is_processed_packet(processed_packet_list, packet)) {
1986                         DEBUG(7,("discarding duplicate packet from %s:%d\n",
1987                                 inet_ntoa(packet->ip),packet->port));
1988                         free_packet(packet);
1989                         continue;
1990                 }
1991
1992                 store_processed_packet(&processed_packet_list, packet);
1993
1994                 /*
1995                  * 0,2,4,... are unicast sockets
1996                  * 1,3,5,... are broadcast sockets
1997                  *
1998                  * on broadcast socket we only receive packets
1999                  * and send replies via the unicast socket.
2000                  *
2001                  * 0,1 and 2,3 and ... belong together.
2002                  */
2003                 if ((i % 2) != 0) {
2004                         /* this is a broadcast socket */
2005                         packet->send_fd = sock_array[i-1];
2006                 } else {
2007                         /* this is already a unicast socket */
2008                         packet->send_fd = sock_array[i];
2009                 }
2010
2011                 queue_packet(packet);
2012         }
2013
2014         free_processed_packet_list(&processed_packet_list);
2015         return False;
2016 }
2017
2018 /****************************************************************************
2019   Construct and send a netbios DGRAM.
2020 **************************************************************************/
2021
2022 bool send_mailslot(bool unique, const char *mailslot,char *buf, size_t len,
2023                    const char *srcname, int src_type,
2024                    const char *dstname, int dest_type,
2025                    struct in_addr dest_ip,struct in_addr src_ip,
2026                    int dest_port)
2027 {
2028         bool loopback_this_packet = False;
2029         struct packet_struct p;
2030         struct dgram_packet *dgram = &p.packet.dgram;
2031         char *ptr,*p2;
2032         char tmp[4];
2033
2034         memset((char *)&p,'\0',sizeof(p));
2035
2036         if(ismyip_v4(dest_ip) && (dest_port == DGRAM_PORT)) /* Only if to DGRAM_PORT */
2037                 loopback_this_packet = True;
2038
2039         /* generate_name_trn_id(); */ /* Not used, so gone, RJS */
2040
2041         /* DIRECT GROUP or UNIQUE datagram. */
2042         dgram->header.msg_type = unique ? 0x10 : 0x11;
2043         dgram->header.flags.node_type = M_NODE;
2044         dgram->header.flags.first = True;
2045         dgram->header.flags.more = False;
2046         dgram->header.dgm_id = generate_name_trn_id();
2047         dgram->header.source_ip = src_ip;
2048         dgram->header.source_port = DGRAM_PORT;
2049         dgram->header.dgm_length = 0; /* Let build_dgram() handle this. */
2050         dgram->header.packet_offset = 0;
2051
2052         make_nmb_name(&dgram->source_name,srcname,src_type);
2053         make_nmb_name(&dgram->dest_name,dstname,dest_type);
2054
2055         ptr = &dgram->data[0];
2056
2057         /* Setup the smb part. */
2058         ptr -= 4; /* XXX Ugliness because of handling of tcp SMB length. */
2059         memcpy(tmp,ptr,4);
2060
2061         if (smb_size + 17*2 + strlen(mailslot) + 1 + len > MAX_DGRAM_SIZE) {
2062                 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
2063                 return false;
2064         }
2065
2066         cli_set_message(ptr,17,strlen(mailslot) + 1 + len,True);
2067         memcpy(ptr,tmp,4);
2068
2069         SCVAL(ptr,smb_com,SMBtrans);
2070         SSVAL(ptr,smb_vwv1,len);
2071         SSVAL(ptr,smb_vwv11,len);
2072         SSVAL(ptr,smb_vwv12,70 + strlen(mailslot));
2073         SSVAL(ptr,smb_vwv13,3);
2074         SSVAL(ptr,smb_vwv14,1);
2075         SSVAL(ptr,smb_vwv15,1);
2076         SSVAL(ptr,smb_vwv16,2);
2077         p2 = smb_buf(ptr);
2078         safe_strcpy_base(p2, mailslot, dgram->data, sizeof(dgram->data));
2079         p2 = skip_string(ptr,MAX_DGRAM_SIZE,p2);
2080
2081         if (((p2+len) > dgram->data+sizeof(dgram->data)) || ((p2+len) < p2)) {
2082                 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
2083                 return False;
2084         } else {
2085                 if (len) {
2086                         memcpy(p2,buf,len);
2087                 }
2088                 p2 += len;
2089         }
2090
2091         dgram->datasize = PTR_DIFF(p2,ptr+4); /* +4 for tcp length. */
2092
2093         p.ip = dest_ip;
2094         p.port = dest_port;
2095         p.recv_fd = -1;
2096         p.send_fd = find_subnet_mailslot_fd_for_address( src_ip );
2097         p.timestamp = time(NULL);
2098         p.packet_type = DGRAM_PACKET;
2099
2100         DEBUG(4,("send_mailslot: Sending to mailslot %s from %s IP %s ", mailslot,
2101                         nmb_namestr(&dgram->source_name), inet_ntoa(src_ip)));
2102         DEBUG(4,("to %s IP %s\n", nmb_namestr(&dgram->dest_name), inet_ntoa(dest_ip)));
2103
2104         debug_browse_data(buf, len);
2105
2106         if(loopback_this_packet) {
2107                 struct packet_struct *lo_packet = NULL;
2108                 DEBUG(5,("send_mailslot: sending packet to ourselves.\n"));
2109                 if((lo_packet = copy_packet(&p)) == NULL)
2110                         return False;
2111                 queue_packet(lo_packet);
2112                 return True;
2113         } else {
2114                 return(send_packet(&p));
2115         }
2116 }