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