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