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