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