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