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