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