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