nmbd_packets.c: nmbd_subnetdb.c: Patch from Andrey Alekseyev <fetch@muffin.arcadia...
[ira/wip.git] / source3 / nmbd / nmbd_packets.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    NBT netbios routines and daemon - version 2
5    Copyright (C) Andrew Tridgell 1994-1998
6    Copyright (C) Luke Kenneth Casson Leighton 1994-1998
7    Copyright (C) Jeremy Allison 1994-1998
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22    
23 */
24
25 #include "includes.h"
26
27 extern int ClientNMB;
28 extern int ClientDGRAM;
29 extern int global_nmb_port;
30
31 extern int DEBUGLEVEL;
32
33 extern int num_response_packets;
34
35 extern pstring scope;
36 extern struct in_addr loopback_ip;
37
38 /*******************************************************************
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  Dispatch a LanMan browse frame from port 138 to the correct processing function.
1028 ****************************************************************************/
1029
1030 void process_lanman_packet(struct packet_struct *p, char *buf,int len)
1031 {
1032   struct dgram_packet *dgram = &p->packet.dgram;
1033   int command = SVAL(buf,0);
1034   struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1035
1036   /* Drop the packet if it's a different NetBIOS scope, or
1037      the source is from one of our names. */
1038
1039   if (!strequal(dgram->dest_name.scope,scope ))
1040   {
1041     DEBUG(7,("process_lanman_packet: Discarding datagram from IP %s. Scope (%s) \
1042 mismatch with our scope (%s).\n", inet_ntoa(p->ip), dgram->dest_name.scope, scope));
1043     return;
1044   }
1045
1046   if (is_myname(dgram->source_name.name))
1047   {
1048     DEBUG(0,("process_lanman_packet: Discarding datagram from IP %s. Source name \
1049 %s is one of our names !\n", inet_ntoa(p->ip), namestr(&dgram->source_name)));
1050     return;
1051   }
1052
1053   switch (command)
1054   {
1055     case ANN_HostAnnouncement:
1056     {
1057       debug_browse_data(buf, len);
1058       process_lm_host_announce(subrec, p, buf+1);
1059       break;
1060     }
1061     case ANN_AnnouncementRequest:
1062     {
1063       process_lm_announce_request(subrec, p, buf+1);
1064       break;
1065     }
1066     default:
1067     {
1068       DEBUG(0,("process_lanman_packet: On subnet %s ignoring browse packet \
1069 command code %d from %s IP %s to %s\n",
1070             subrec->subnet_name, command, namestr(&dgram->source_name),
1071             inet_ntoa(p->ip), namestr(&dgram->dest_name)));
1072     }
1073   }
1074 }
1075
1076 /****************************************************************************
1077   Determine if a packet is for us on port 138. Note that to have any chance of
1078   being efficient we need to drop as many packets as possible at this
1079   stage as subsequent processing is expensive. 
1080 ****************************************************************************/
1081
1082 static BOOL listening(struct packet_struct *p,struct nmb_name *nbname)
1083 {
1084   struct subnet_record *subrec = NULL;
1085
1086   for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1087   {
1088     if(same_net(p->ip, subrec->bcast_ip, subrec->mask_ip))
1089       break;
1090   }
1091
1092   if(subrec == NULL)
1093     subrec = unicast_subnet;
1094
1095   return (find_name_on_subnet(subrec, nbname, FIND_SELF_NAME) != NULL);
1096 }
1097
1098 /****************************************************************************
1099   Process udp 138 datagrams
1100 ****************************************************************************/
1101
1102 static void process_dgram(struct packet_struct *p)
1103 {
1104   char *buf;
1105   char *buf2;
1106   int len;
1107   struct dgram_packet *dgram = &p->packet.dgram;
1108
1109   /* If we aren't listening to the destination name then ignore the packet */
1110   if (!listening(p,&dgram->dest_name))
1111   {
1112     DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from %s\n",
1113            namestr(&dgram->dest_name), inet_ntoa(p->ip)));
1114     return;
1115   }
1116
1117   if (dgram->header.msg_type != 0x10 &&
1118       dgram->header.msg_type != 0x11 &&
1119       dgram->header.msg_type != 0x12) 
1120   {
1121     /* Don't process error packets etc yet */
1122     DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from IP %s as it is \
1123            an error packet of type %x\n",
1124            namestr(&dgram->dest_name), inet_ntoa(p->ip), dgram->header.msg_type));
1125     return;
1126   }
1127
1128   buf = &dgram->data[0];
1129   buf -= 4; /* XXXX for the pseudo tcp length - 
1130                someday I need to get rid of this */
1131
1132   if (CVAL(buf,smb_com) != SMBtrans)
1133     return;
1134
1135   len = SVAL(buf,smb_vwv11);
1136   buf2 = smb_base(buf) + SVAL(buf,smb_vwv12);
1137
1138   DEBUG(4,("process_dgram: datagram from %s to %s IP %s for %s of type %d len=%d\n",
1139            namestr(&dgram->source_name),namestr(&dgram->dest_name),
1140            inet_ntoa(p->ip), smb_buf(buf),CVAL(buf2,0),len));
1141
1142  
1143   if (len <= 0)
1144     return;
1145
1146   /* Datagram packet received for the browser mailslot */
1147   if (strequal(smb_buf(buf),BROWSE_MAILSLOT))
1148   {
1149     process_browse_packet(p,buf2,len);
1150     return;
1151   }
1152
1153   /* Datagram packet received for the LAN Manager mailslot */
1154   if (strequal(smb_buf(buf),LANMAN_MAILSLOT)) {
1155     process_lanman_packet(p,buf2,len);
1156     return;
1157   }
1158
1159   /* Datagram packet received for the domain logon mailslot */
1160   if (strequal(smb_buf(buf),NET_LOGON_MAILSLOT))
1161   {
1162     process_logon_packet(p,buf2,len,NET_LOGON_MAILSLOT);
1163     return;
1164   }
1165
1166   /* Datagram packet received for the NT domain logon mailslot */
1167   if (strequal(smb_buf(buf),NT_LOGON_MAILSLOT))
1168   {
1169     process_logon_packet(p,buf2,len,NT_LOGON_MAILSLOT);
1170     return;
1171   }
1172 }
1173
1174 /****************************************************************************
1175   Validate a response nmb packet.
1176 ****************************************************************************/
1177
1178 BOOL validate_nmb_response_packet( struct nmb_packet *nmb )
1179 {
1180   BOOL ignore = False;
1181
1182   switch (nmb->header.opcode) 
1183   {
1184     case NMB_NAME_REG_OPCODE:
1185     case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1186     case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1187       if (nmb->header.ancount == 0)
1188       {
1189         DEBUG(0,("validate_nmb_response_packet: Bad REG/REFRESH Packet. "));
1190         ignore = True;
1191       }
1192       break;
1193
1194     case NMB_NAME_QUERY_OPCODE:
1195       if ((nmb->header.ancount != 0) && (nmb->header.ancount != 1))
1196       {
1197         DEBUG(0,("validate_nmb_response_packet: Bad QUERY Packet. "));
1198         ignore = True;
1199       }
1200       break;
1201     case NMB_NAME_RELEASE_OPCODE:
1202       if (nmb->header.ancount == 0)
1203       {
1204         DEBUG(0,("validate_nmb_response_packet: Bad RELEASE Packet. "));
1205         ignore = True;
1206       }
1207       break;
1208     case NMB_WACK_OPCODE:
1209       /* Check WACK response here. */
1210       if (nmb->header.ancount != 1)
1211       {
1212         DEBUG(0,("validate_nmb_response_packet: Bad WACK Packet. "));
1213         ignore = True;
1214       }
1215       break;
1216     default:
1217       DEBUG(0,("validate_nmb_response_packet: Ignoring packet with unknown opcode %d.\n",
1218         nmb->header.opcode));
1219       return True;
1220   }
1221
1222   if(ignore)
1223     DEBUG(0,("Ignoring response packet with opcode %d.\n", nmb->header.opcode));
1224
1225   return ignore;
1226 }
1227  
1228 /****************************************************************************
1229   Validate a request nmb packet.
1230 ****************************************************************************/
1231
1232 BOOL validate_nmb_packet( struct nmb_packet *nmb )
1233 {
1234   BOOL ignore = False;
1235
1236   switch (nmb->header.opcode) 
1237   {
1238     case NMB_NAME_REG_OPCODE:
1239     case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1240     case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1241     case NMB_NAME_MULTIHOMED_REG_OPCODE:
1242       if (nmb->header.qdcount==0 || nmb->header.arcount==0)
1243       {
1244         DEBUG(0,("validate_nmb_packet: Bad REG/REFRESH Packet. "));
1245         ignore = True;
1246       }
1247       break;
1248
1249     case NMB_NAME_QUERY_OPCODE:
1250       if ((nmb->header.qdcount == 0) || 
1251          ((nmb->question.question_type != QUESTION_TYPE_NB_QUERY) &&
1252          (nmb->question.question_type != QUESTION_TYPE_NB_STATUS)))
1253       {
1254         DEBUG(0,("validate_nmb_packet: Bad QUERY Packet. "));
1255         ignore = True;
1256       }
1257       break;
1258
1259     case NMB_NAME_RELEASE_OPCODE:
1260       if (nmb->header.qdcount==0 || nmb->header.arcount==0)
1261       {
1262         DEBUG(0,("validate_nmb_packet: Bad RELEASE Packet. "));
1263         ignore = True;
1264       }
1265       break;
1266     default:
1267       DEBUG(0,("validate_nmb_packet: Ignoring packet with unknown opcode %d.\n",
1268         nmb->header.opcode));
1269       return True;
1270   }
1271
1272   if(ignore)
1273     DEBUG(0,("validate_nmb_packet: Ignoring request packet with opcode %d.\n", nmb->header.opcode));
1274
1275   return ignore;
1276 }
1277
1278 /****************************************************************************
1279   Find a subnet (and potentially a response record) for a packet.
1280 ****************************************************************************/
1281
1282 static struct subnet_record *find_subnet_for_nmb_packet( struct packet_struct *p,
1283                                                          struct response_record **pprrec)
1284 {
1285   struct nmb_packet *nmb = &p->packet.nmb;
1286   struct response_record *rrec = NULL;
1287   struct subnet_record *subrec = NULL;
1288
1289   if(pprrec != NULL)
1290     *pprrec = NULL;
1291
1292   if(nmb->header.response)
1293   {
1294     /* It's a response packet. Find a record for it or it's an error. */
1295
1296     rrec = find_response_record( &subrec, nmb->header.name_trn_id);
1297     if(rrec == NULL)
1298     {
1299       DEBUG(0,("find_subnet_for_nmb_packet: response record not found for response id %hu\n",
1300                nmb->header.name_trn_id));
1301       return NULL;
1302     }
1303
1304     if(subrec == NULL)
1305     {
1306       DEBUG(0,("find_subnet_for_nmb_packet: subnet record not found for response id %hu\n",
1307                nmb->header.name_trn_id));
1308       return NULL;
1309     }
1310
1311     if(pprrec != NULL)
1312       *pprrec = rrec;
1313     return subrec;
1314   }
1315
1316   /* Try and see what subnet this packet belongs to. */
1317
1318   /* WINS server ? */
1319   if(packet_is_for_wins_server(p))
1320     return wins_server_subnet;
1321
1322   /* If it wasn't a broadcast packet then send to the UNICAST subnet. */
1323   if(nmb->header.nm_flags.bcast == False)
1324     return unicast_subnet;
1325
1326   /* Go through all the broadcast subnets and see if the mask matches. */
1327   for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1328   {
1329     if(same_net(p->ip, subrec->bcast_ip, subrec->mask_ip))
1330       return subrec;
1331   }
1332
1333   /* If none match it must have been a directed broadcast - assign
1334      the remote_broadcast_subnet. */
1335   return remote_broadcast_subnet;
1336 }
1337
1338 /****************************************************************************
1339   Process a nmb request packet - validate the packet and route it.
1340 ****************************************************************************/
1341
1342 static void process_nmb_request(struct packet_struct *p)
1343 {
1344   struct nmb_packet *nmb = &p->packet.nmb;
1345   struct subnet_record *subrec = NULL;
1346
1347   debug_nmb_packet(p);
1348
1349   /* Ensure we have a good packet. */
1350   if(validate_nmb_packet(nmb))
1351     return;
1352
1353   /* Allocate a subnet to this packet - if we cannot - fail. */
1354   if((subrec = find_subnet_for_nmb_packet(p, NULL))==NULL)
1355     return;
1356
1357   switch (nmb->header.opcode) 
1358   {
1359     case NMB_NAME_REG_OPCODE:
1360       if(subrec == wins_server_subnet)
1361         wins_process_name_registration_request(subrec, p);
1362       else
1363         process_name_registration_request(subrec, p);
1364       break;
1365
1366     case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1367     case NMB_NAME_REFRESH_OPCODE_9:
1368       if(subrec == wins_server_subnet)
1369         wins_process_name_refresh_request(subrec, p);
1370       else
1371         process_name_refresh_request(subrec, p);
1372       break;
1373
1374     case NMB_NAME_MULTIHOMED_REG_OPCODE:
1375       if(subrec == wins_server_subnet)
1376         wins_process_multihomed_name_registration_request(subrec, p);
1377       else
1378       {
1379         DEBUG(0,("process_nmb_request: Multihomed registration request must be \
1380 directed at a WINS server.\n"));
1381       }
1382       break;
1383
1384     case NMB_NAME_QUERY_OPCODE:
1385       switch (nmb->question.question_type)
1386       {
1387         case QUESTION_TYPE_NB_QUERY:
1388         {
1389           if(subrec == wins_server_subnet)
1390             wins_process_name_query_request(subrec, p);
1391           else
1392             process_name_query_request(subrec, p);
1393           break;
1394         }
1395         case QUESTION_TYPE_NB_STATUS:
1396         {
1397           if(subrec == wins_server_subnet)
1398           {
1399             DEBUG(0,("process_nmb_request: NB_STATUS request directed at WINS server is \
1400 not allowed.\n"));
1401             break;
1402           }
1403           else
1404             process_node_status_request(subrec, p);
1405           break;
1406         }
1407       }
1408       break;
1409       
1410     case NMB_NAME_RELEASE_OPCODE:
1411       if(subrec == wins_server_subnet)
1412         wins_process_name_release_request(subrec, p);
1413       else
1414         process_name_release_request(subrec, p);
1415       break;
1416   }
1417 }
1418
1419 /****************************************************************************
1420   Process a nmb response packet - validate the packet and route it.
1421   to either the WINS server or a normal response.
1422 ****************************************************************************/
1423
1424 static void process_nmb_response(struct packet_struct *p)
1425 {
1426   struct nmb_packet *nmb = &p->packet.nmb;
1427   struct subnet_record *subrec = NULL;
1428   struct response_record *rrec = NULL;
1429
1430   debug_nmb_packet(p);
1431
1432   if(validate_nmb_response_packet(nmb))
1433     return;
1434
1435   if((subrec = find_subnet_for_nmb_packet(p, &rrec))==NULL)
1436     return;
1437
1438   if(rrec == NULL)
1439   {
1440     DEBUG(0,("process_nmb_response: response packet received but no response record \
1441 found for id = %hu. Ignoring packet.\n", nmb->header.name_trn_id));
1442     return;
1443   }
1444
1445   /* Increment the number of responses received for this record. */
1446   rrec->num_msgs++;
1447   /* Ensure we don't re-send the request. */
1448   rrec->repeat_count = 0;
1449   
1450   /* Call the response received function for this packet. */
1451   (*rrec->resp_fn)(subrec, rrec, p);
1452 }
1453
1454
1455 /*******************************************************************
1456   Run elements off the packet queue till its empty
1457 ******************************************************************/
1458
1459 void run_packet_queue()
1460 {
1461   struct packet_struct *p;
1462
1463   while ((p = packet_queue))
1464   {
1465     packet_queue = p->next;
1466     if (packet_queue)
1467       packet_queue->prev = NULL;
1468     p->next = p->prev = NULL;
1469
1470     switch (p->packet_type)
1471     {
1472       case NMB_PACKET:
1473         if(p->packet.nmb.header.response)
1474           process_nmb_response(p);
1475         else
1476           process_nmb_request(p);
1477         break;
1478
1479       case DGRAM_PACKET:
1480         process_dgram(p);
1481         break;
1482     }
1483     free_packet(p);
1484   }
1485
1486
1487 /*******************************************************************
1488  Retransmit or timeout elements from all the outgoing subnet response
1489  record queues. NOTE that this code must also check the WINS server
1490  subnet for response records to timeout as the WINS server code
1491  can send requests to check if a client still owns a name.
1492  (Patch from Andrey Alekseyev <fetch@muffin.arcadia.spb.ru>).
1493 ******************************************************************/
1494
1495 void retransmit_or_expire_response_records(time_t t)
1496 {
1497   struct subnet_record *subrec;
1498
1499   for (subrec = FIRST_SUBNET; subrec; 
1500                subrec = get_next_subnet_maybe_unicast_or_wins_server(subrec))
1501   {
1502     struct response_record *rrec, *nextrrec;
1503
1504     for (rrec = subrec->responselist; rrec; rrec = nextrrec)
1505     {
1506       nextrrec = rrec->next;
1507    
1508       if (rrec->repeat_time <= t) 
1509       {
1510         if (rrec->repeat_count > 0)
1511         {
1512           /* Resend while we have a non-zero repeat_count. */
1513           if(!send_packet(rrec->packet))
1514           {
1515             DEBUG(0,("retransmit_or_expire_response_records: Failed to resend packet id %hu \
1516 to IP %s on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), 
1517                           subrec->subnet_name));
1518           }
1519           rrec->repeat_time += rrec->repeat_interval;
1520           rrec->repeat_count--;
1521         }
1522         else
1523         {
1524           DEBUG(4,("retransmit_or_expire_response_records: timeout for packet id %hu to IP %s \
1525 on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), 
1526                  subrec->subnet_name));
1527
1528           /* Call the timeout function. This will deal with removing the
1529              timed out packet. */
1530           if(rrec->timeout_fn)
1531             (*rrec->timeout_fn)(subrec, rrec);
1532           else
1533           {
1534             /* We must remove the record ourself if there is
1535                no timeout function. */
1536             remove_response_record(subrec, rrec);
1537           }
1538         } /* rrec->repeat_count > 0 */
1539       } /* rrec->repeat_time <= t */
1540     } /* end for rrec */
1541   } /* end for subnet */
1542 }
1543
1544 /****************************************************************************
1545   Create an fd_set containing all the sockets in the subnet structures,
1546   plus the broadcast sockets.
1547 ***************************************************************************/
1548
1549 static BOOL create_listen_fdset(fd_set **ppset, int **psock_array, int *listen_number)
1550 {
1551   int *sock_array = NULL;
1552   struct subnet_record *subrec = NULL;
1553   int count = 0;
1554   int num = 0;
1555   fd_set *pset = (fd_set *)malloc(sizeof(fd_set));
1556
1557   if(pset == NULL)
1558   {
1559     DEBUG(0,("create_listen_fdset: malloc fail !\n"));
1560     return True;
1561   }
1562
1563   /* Check that we can add all the fd's we need. */
1564   for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1565     count++;
1566
1567   if((count*2) + 2 > FD_SETSIZE)
1568   {
1569     DEBUG(0,("create_listen_fdset: Too many file descriptors needed (%d). We can \
1570 only use %d.\n", (count*2) + 2, FD_SETSIZE));
1571     return True;
1572   }
1573
1574   if((sock_array = (int *)malloc(((count*2) + 2)*sizeof(int))) == NULL)
1575   {
1576     DEBUG(0,("create_listen_fdset: malloc fail for socket array.\n"));
1577     return True;
1578   }
1579
1580   FD_ZERO(pset);
1581
1582   /* Add in the broadcast socket on 137. */
1583   FD_SET(ClientNMB,pset);
1584   sock_array[num++] = ClientNMB;
1585
1586   /* Add in the 137 sockets on all the interfaces. */
1587   for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1588   {
1589     FD_SET(subrec->nmb_sock,pset);
1590     sock_array[num++] = subrec->nmb_sock;
1591   }
1592
1593   /* Add in the broadcast socket on 138. */
1594   FD_SET(ClientDGRAM,pset);
1595   sock_array[num++] = ClientDGRAM;
1596
1597   /* Add in the 138 sockets on all the interfaces. */
1598   for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1599   {
1600     FD_SET(subrec->dgram_sock,pset);
1601     sock_array[num++] = subrec->dgram_sock;
1602   }
1603
1604   *listen_number = (count*2) + 2;
1605   *ppset = pset;
1606   *psock_array = sock_array;
1607  
1608   return False;
1609 }
1610
1611 /****************************************************************************
1612   Listens for NMB or DGRAM packets, and queues them.
1613 ***************************************************************************/
1614
1615 BOOL listen_for_packets(BOOL run_election)
1616 {
1617   static fd_set *listen_set = NULL;
1618   static int listen_number = 0;
1619   static int *sock_array = NULL;
1620
1621   fd_set fds;
1622   int selrtn;
1623   struct timeval timeout;
1624 #ifndef SYNC_DNS
1625   int dns_fd;
1626 #endif
1627
1628   if(listen_set == NULL)
1629   {
1630     if(create_listen_fdset(&listen_set, &sock_array, &listen_number))
1631     {
1632       DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
1633       return True;
1634     }
1635   }
1636
1637   memcpy((char *)&fds, (char *)listen_set, sizeof(fd_set));
1638
1639 #ifndef SYNC_DNS
1640   dns_fd = asyncdns_fd();
1641   if (dns_fd != -1) {
1642           FD_SET(dns_fd, &fds);
1643   }
1644 #endif
1645
1646
1647   /* 
1648    * During elections and when expecting a netbios response packet we
1649    * need to send election packets at tighter intervals.
1650    * Ideally it needs to be the interval (in ms) between time now and
1651    * the time we are expecting the next netbios packet.
1652    */
1653
1654   timeout.tv_sec = (run_election||num_response_packets) ? 1 : NMBD_SELECT_LOOP;
1655   timeout.tv_usec = 0;
1656
1657   /* Prepare for the select - allow certain signals. */
1658
1659   BlockSignals(False, SIGTERM);
1660 #if defined(SIGUSR1)
1661   BlockSignals(False, SIGUSR1);
1662 #endif /* SIGUSR1 */
1663 #if defined(SIGUSR2)
1664   BlockSignals(False, SIGUSR2);
1665 #endif /* SIGUSR2 */
1666
1667   selrtn = sys_select(&fds,&timeout);
1668
1669   /* We can only take signals when we are in the select - block them again here. */
1670
1671   BlockSignals(True, SIGTERM);
1672 #if defined(SIGUSR1)
1673   BlockSignals(True, SIGUSR1);
1674 #endif /* SIGUSR1 */
1675 #if defined(SIGUSR2)
1676   BlockSignals(True, SIGUSR2);
1677 #endif /* SIGUSR2 */
1678
1679   if(selrtn > 0)
1680   {
1681     int i;
1682
1683 #ifndef SYNC_DNS
1684     if (dns_fd != -1 && FD_ISSET(dns_fd,&fds)) {
1685             run_dns_queue();
1686     }
1687 #endif
1688
1689     for(i = 0; i < listen_number; i++)
1690     {
1691       if(i < (listen_number/2))
1692       {
1693         /* Processing a 137 socket. */
1694         if (FD_ISSET(sock_array[i],&fds))
1695         {
1696           struct packet_struct *packet = read_packet(sock_array[i], NMB_PACKET);
1697           if (packet)
1698           {
1699             /*
1700              * If we got a packet on the broadcast socket and interfaces
1701              * only is set then check it came from one of our local nets. 
1702              */
1703             if(lp_bind_interfaces_only() && (sock_array[i] == ClientNMB) && 
1704                (!is_local_net(packet->ip)))
1705             {
1706               DEBUG(7,("discarding nmb packet sent to broadcast socket from %s:%d\n",
1707                         inet_ntoa(packet->ip),packet->port));     
1708               free_packet(packet);
1709             }
1710             else if ((ip_equal(loopback_ip, packet->ip) || 
1711               ismyip(packet->ip)) && packet->port == global_nmb_port)
1712             {
1713               DEBUG(7,("discarding own packet from %s:%d\n",
1714                         inet_ntoa(packet->ip),packet->port));     
1715               free_packet(packet);
1716             }
1717             else
1718             {
1719               /* Save the file descriptor this packet came in on. */
1720               packet->fd = sock_array[i];
1721               queue_packet(packet);
1722             }
1723           }
1724         }
1725       }
1726       else
1727       {
1728         /* Processing a 138 socket. */
1729
1730         if (FD_ISSET(sock_array[i],&fds))
1731         {
1732           struct packet_struct *packet = read_packet(sock_array[i], DGRAM_PACKET);
1733           if (packet)
1734           {
1735             /*
1736              * If we got a packet on the broadcast socket and interfaces
1737              * only is set then check it came from one of our local nets. 
1738              */
1739             if(lp_bind_interfaces_only() && (sock_array[i] == ClientDGRAM) && 
1740                  (!is_local_net(packet->ip)))
1741             {
1742               DEBUG(7,("discarding dgram packet sent to broadcast socket from %s:%d\n",
1743                         inet_ntoa(packet->ip),packet->port));     
1744               free_packet(packet);
1745             }
1746             else if ((ip_equal(loopback_ip, packet->ip) || 
1747                  ismyip(packet->ip)) && packet->port == DGRAM_PORT)
1748             {
1749               DEBUG(7,("discarding own packet from %s:%d\n",
1750                         inet_ntoa(packet->ip),packet->port));     
1751               free_packet(packet);
1752             }
1753             else
1754             {
1755               /* Save the file descriptor this packet came in on. */
1756               packet->fd = sock_array[i];
1757               queue_packet(packet);
1758             }
1759           }
1760         }
1761       } /* end processing 138 socket. */
1762     } /* end for */
1763   } /* end if selret > 0 */
1764   return False;
1765 }
1766
1767 /****************************************************************************
1768   Construct and send a netbios DGRAM.
1769   Note that this currently sends all packets to port 138.
1770 **************************************************************************/
1771
1772 BOOL send_mailslot(BOOL unique, char *mailslot,char *buf,int len,
1773                    char *srcname, int src_type,
1774                    char *dstname, int dest_type,
1775                    struct in_addr dest_ip,struct in_addr src_ip)
1776 {
1777   BOOL loopback_this_packet = False;
1778   struct packet_struct p;
1779   struct dgram_packet *dgram = &p.packet.dgram;
1780   char *ptr,*p2;
1781   char tmp[4];
1782
1783   bzero((char *)&p,sizeof(p));
1784
1785   if(ismyip(dest_ip))
1786     loopback_this_packet = True;
1787
1788   generate_name_trn_id();
1789
1790   /* DIRECT GROUP or UNIQUE datagram. */
1791   dgram->header.msg_type = unique ? 0x10 : 0x11; 
1792   dgram->header.flags.node_type = M_NODE;
1793   dgram->header.flags.first = True;
1794   dgram->header.flags.more = False;
1795   dgram->header.dgm_id = name_trn_id;
1796   dgram->header.source_ip = src_ip;
1797   dgram->header.source_port = DGRAM_PORT;
1798   dgram->header.dgm_length = 0; /* Let build_dgram() handle this. */
1799   dgram->header.packet_offset = 0;
1800   
1801   make_nmb_name(&dgram->source_name,srcname,src_type,scope);
1802   make_nmb_name(&dgram->dest_name,dstname,dest_type,scope);
1803
1804   ptr = &dgram->data[0];
1805
1806   /* Setup the smb part. */
1807   ptr -= 4; /* XXX Ugliness because of handling of tcp SMB length. */
1808   memcpy(tmp,ptr,4);
1809   set_message(ptr,17,17 + len,True);
1810   memcpy(ptr,tmp,4);
1811
1812   CVAL(ptr,smb_com) = SMBtrans;
1813   SSVAL(ptr,smb_vwv1,len);
1814   SSVAL(ptr,smb_vwv11,len);
1815   SSVAL(ptr,smb_vwv12,70 + strlen(mailslot));
1816   SSVAL(ptr,smb_vwv13,3);
1817   SSVAL(ptr,smb_vwv14,1);
1818   SSVAL(ptr,smb_vwv15,1);
1819   SSVAL(ptr,smb_vwv16,2);
1820   p2 = smb_buf(ptr);
1821   strcpy(p2,mailslot);
1822   p2 = skip_string(p2,1);
1823
1824   memcpy(p2,buf,len);
1825   p2 += len;
1826
1827   dgram->datasize = PTR_DIFF(p2,ptr+4); /* +4 for tcp length. */
1828
1829   p.ip = dest_ip;
1830   p.port = DGRAM_PORT;
1831   p.fd = ClientDGRAM;
1832   p.timestamp = time(NULL);
1833   p.packet_type = DGRAM_PACKET;
1834
1835   DEBUG(4,("send_mailslot: Sending to mailslot %s from %s IP %s ", mailslot,
1836                     namestr(&dgram->source_name), inet_ntoa(src_ip)));
1837   DEBUG(4,("to %s IP %s\n", namestr(&dgram->dest_name), inet_ntoa(dest_ip)));
1838
1839   debug_browse_data(buf, len);
1840
1841   if(loopback_this_packet)
1842   {
1843     struct packet_struct *lo_packet = NULL;
1844     DEBUG(5,("send_mailslot: sending packet to ourselves.\n"));
1845     if((lo_packet = copy_packet(&p)) == NULL)
1846       return False;
1847     queue_packet(lo_packet);
1848     return True;
1849   }
1850   else
1851     return(send_packet(&p));
1852 }