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