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