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