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