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