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