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