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