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