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