s3: Fix Coverity ID 2331: RESOURCE_LEAK
[Samba.git] / source3 / nmbd / nmbd_packets.c
blob36dacfb6f31f8c1b53693d37aceea1325035fc73
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
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.
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.
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/>.
22 #include "includes.h"
23 #include "nmbd/nmbd.h"
24 #include "../lib/util/select.h"
25 #include "system/select.h"
27 extern int ClientNMB;
28 extern int ClientDGRAM;
29 extern int global_nmb_port;
31 extern int num_response_packets;
33 bool rescan_listen_set = False;
35 static struct nb_packet_server *packet_server;
37 bool nmbd_init_packet_server(void)
39 NTSTATUS status;
41 status = nb_packet_server_create(
42 NULL, nmbd_event_context(),
43 lp_parm_int(-1, "nmbd", "unexpected_clients", 200),
44 &packet_server);
45 if (!NT_STATUS_IS_OK(status)) {
46 DEBUG(0, ("ERROR: nb_packet_server_create failed: %s\n",
47 nt_errstr(status)));
48 return false;
50 return true;
54 /*******************************************************************
55 The global packet linked-list. Incoming entries are
56 added to the end of this list. It is supposed to remain fairly
57 short so we won't bother with an end pointer.
58 ******************************************************************/
60 static struct packet_struct *packet_queue = NULL;
62 /***************************************************************************
63 Utility function to find the specific fd to send a packet out on.
64 **************************************************************************/
66 static int find_subnet_fd_for_address( struct in_addr local_ip )
68 struct subnet_record *subrec;
70 for( subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
71 if(ip_equal_v4(local_ip, subrec->myip))
72 return subrec->nmb_sock;
74 return ClientNMB;
77 /***************************************************************************
78 Utility function to find the specific fd to send a mailslot packet out on.
79 **************************************************************************/
81 static int find_subnet_mailslot_fd_for_address( struct in_addr local_ip )
83 struct subnet_record *subrec;
85 for( subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
86 if(ip_equal_v4(local_ip, subrec->myip))
87 return subrec->dgram_sock;
89 return ClientDGRAM;
92 /***************************************************************************
93 Get/Set problematic nb_flags as network byte order 16 bit int.
94 **************************************************************************/
96 uint16 get_nb_flags(char *buf)
98 return ((((uint16)*buf)&0xFFFF) & NB_FLGMSK);
101 void set_nb_flags(char *buf, uint16 nb_flags)
103 *buf++ = ((nb_flags & NB_FLGMSK) & 0xFF);
104 *buf = '\0';
107 /***************************************************************************
108 Dumps out the browse packet data.
109 **************************************************************************/
111 static void debug_browse_data(char *outbuf, int len)
113 int i,j;
115 DEBUG( 4, ( "debug_browse_data():\n" ) );
116 for (i = 0; i < len; i+= 16) {
117 DEBUGADD( 4, ( "%3x char ", i ) );
119 for (j = 0; j < 16; j++) {
120 unsigned char x;
121 if (i+j >= len)
122 break;
124 x = outbuf[i+j];
125 if (x < 32 || x > 127)
126 x = '.';
128 DEBUGADD( 4, ( "%c", x ) );
131 DEBUGADD( 4, ( "%*s hex", 16-j, "" ) );
133 for (j = 0; j < 16; j++) {
134 if (i+j >= len)
135 break;
136 DEBUGADD( 4, ( " %02x", (unsigned char)outbuf[i+j] ) );
139 DEBUGADD( 4, ("\n") );
143 /***************************************************************************
144 Generates the unique transaction identifier
145 **************************************************************************/
147 static uint16 name_trn_id=0;
149 static uint16 generate_name_trn_id(void)
151 if (!name_trn_id) {
152 name_trn_id = ((unsigned)time(NULL)%(unsigned)0x7FFF) + ((unsigned)sys_getpid()%(unsigned)100);
154 name_trn_id = (name_trn_id+1) % (unsigned)0x7FFF;
155 return name_trn_id;
158 /***************************************************************************
159 Either loops back or sends out a completed NetBIOS packet.
160 **************************************************************************/
162 static bool send_netbios_packet(struct packet_struct *p)
164 bool loopback_this_packet = False;
166 /* Check if we are sending to or from ourselves as a WINS server. */
167 if(ismyip_v4(p->ip) && (p->port == global_nmb_port))
168 loopback_this_packet = True;
170 if(loopback_this_packet) {
171 struct packet_struct *lo_packet = NULL;
172 DEBUG(5,("send_netbios_packet: sending packet to ourselves.\n"));
173 if((lo_packet = copy_packet(p)) == NULL)
174 return False;
175 queue_packet(lo_packet);
176 } else if (!send_packet(p)) {
177 DEBUG(0,("send_netbios_packet: send_packet() to IP %s port %d failed\n",
178 inet_ntoa(p->ip),p->port));
179 return False;
182 return True;
185 /***************************************************************************
186 Sets up the common elements of an outgoing NetBIOS packet.
188 Note: do not attempt to rationalise whether rec_des should be set or not
189 in a particular situation. Just follow rfc_1002 or look at examples from WinXX.
190 It does NOT follow the rule that requests to the wins server always have
191 rec_des true. See for example name releases and refreshes
192 **************************************************************************/
194 static struct packet_struct *create_and_init_netbios_packet(struct nmb_name *nmbname,
195 bool bcast, bool rec_des,
196 struct in_addr to_ip)
198 struct packet_struct *packet = NULL;
199 struct nmb_packet *nmb = NULL;
201 /* Allocate the packet_struct we will return. */
202 if((packet = SMB_MALLOC_P(struct packet_struct)) == NULL) {
203 DEBUG(0,("create_and_init_netbios_packet: malloc fail (1) for packet struct.\n"));
204 return NULL;
207 memset((char *)packet,'\0',sizeof(*packet));
209 nmb = &packet->packet.nmb;
211 nmb->header.name_trn_id = generate_name_trn_id();
212 nmb->header.response = False;
213 nmb->header.nm_flags.recursion_desired = rec_des;
214 nmb->header.nm_flags.recursion_available = False;
215 nmb->header.nm_flags.trunc = False;
216 nmb->header.nm_flags.authoritative = False;
217 nmb->header.nm_flags.bcast = bcast;
219 nmb->header.rcode = 0;
220 nmb->header.qdcount = 1;
221 nmb->header.ancount = 0;
222 nmb->header.nscount = 0;
224 nmb->question.question_name = *nmbname;
225 nmb->question.question_type = QUESTION_TYPE_NB_QUERY;
226 nmb->question.question_class = QUESTION_CLASS_IN;
228 packet->ip = to_ip;
229 packet->port = NMB_PORT;
230 packet->recv_fd = -1;
231 packet->send_fd = ClientNMB;
232 packet->timestamp = time(NULL);
233 packet->packet_type = NMB_PACKET;
234 packet->locked = False;
236 return packet; /* Caller must free. */
239 /***************************************************************************
240 Sets up the common elements of register, refresh or release packet.
241 **************************************************************************/
243 static bool create_and_init_additional_record(struct packet_struct *packet,
244 uint16 nb_flags,
245 const struct in_addr *register_ip)
247 struct nmb_packet *nmb = &packet->packet.nmb;
249 if((nmb->additional = SMB_MALLOC_P(struct res_rec)) == NULL) {
250 DEBUG(0,("create_and_init_additional_record: malloc fail for additional record.\n"));
251 return False;
254 memset((char *)nmb->additional,'\0',sizeof(struct res_rec));
256 nmb->additional->rr_name = nmb->question.question_name;
257 nmb->additional->rr_type = RR_TYPE_NB;
258 nmb->additional->rr_class = RR_CLASS_IN;
260 /* See RFC 1002, sections 5.1.1.1, 5.1.1.2 and 5.1.1.3 */
261 if (nmb->header.nm_flags.bcast)
262 nmb->additional->ttl = PERMANENT_TTL;
263 else
264 nmb->additional->ttl = lp_max_ttl();
266 nmb->additional->rdlength = 6;
268 set_nb_flags(nmb->additional->rdata,nb_flags);
270 /* Set the address for the name we are registering. */
271 putip(&nmb->additional->rdata[2], register_ip);
274 it turns out that Jeremys code was correct, we are supposed
275 to send registrations from the IP we are registering. The
276 trick is what to do on timeouts! When we send on a
277 non-routable IP then the reply will timeout, and we should
278 treat this as success, not failure. That means we go into
279 our standard refresh cycle for that name which copes nicely
280 with disconnected networks.
282 packet->recv_fd = -1;
283 packet->send_fd = find_subnet_fd_for_address(*register_ip);
285 return True;
288 /***************************************************************************
289 Sends out a name query.
290 **************************************************************************/
292 static bool initiate_name_query_packet( struct packet_struct *packet)
294 struct nmb_packet *nmb = NULL;
296 nmb = &packet->packet.nmb;
298 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
299 nmb->header.arcount = 0;
301 nmb->header.nm_flags.recursion_desired = True;
303 DEBUG(4,("initiate_name_query_packet: sending query for name %s (bcast=%s) to IP %s\n",
304 nmb_namestr(&nmb->question.question_name),
305 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
307 return send_netbios_packet( packet );
310 /***************************************************************************
311 Sends out a name query - from a WINS server.
312 **************************************************************************/
314 static bool initiate_name_query_packet_from_wins_server( struct packet_struct *packet)
316 struct nmb_packet *nmb = NULL;
318 nmb = &packet->packet.nmb;
320 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
321 nmb->header.arcount = 0;
323 nmb->header.nm_flags.recursion_desired = False;
325 DEBUG(4,("initiate_name_query_packet_from_wins_server: sending query for name %s (bcast=%s) to IP %s\n",
326 nmb_namestr(&nmb->question.question_name),
327 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
329 return send_netbios_packet( packet );
332 /***************************************************************************
333 Sends out a name register.
334 **************************************************************************/
336 static bool initiate_name_register_packet( struct packet_struct *packet,
337 uint16 nb_flags, const struct in_addr *register_ip)
339 struct nmb_packet *nmb = &packet->packet.nmb;
341 nmb->header.opcode = NMB_NAME_REG_OPCODE;
342 nmb->header.arcount = 1;
344 nmb->header.nm_flags.recursion_desired = True;
346 if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
347 return False;
349 DEBUG(4,("initiate_name_register_packet: sending registration for name %s (bcast=%s) to IP %s\n",
350 nmb_namestr(&nmb->additional->rr_name),
351 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
353 return send_netbios_packet( packet );
356 /***************************************************************************
357 Sends out a multihomed name register.
358 **************************************************************************/
360 static bool initiate_multihomed_name_register_packet(struct packet_struct *packet,
361 uint16 nb_flags, struct in_addr *register_ip)
363 struct nmb_packet *nmb = &packet->packet.nmb;
364 fstring second_ip_buf;
366 fstrcpy(second_ip_buf, inet_ntoa(packet->ip));
368 nmb->header.opcode = NMB_NAME_MULTIHOMED_REG_OPCODE;
369 nmb->header.arcount = 1;
371 nmb->header.nm_flags.recursion_desired = True;
373 if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
374 return False;
376 DEBUG(4,("initiate_multihomed_name_register_packet: sending registration \
377 for name %s IP %s (bcast=%s) to IP %s\n",
378 nmb_namestr(&nmb->additional->rr_name), inet_ntoa(*register_ip),
379 BOOLSTR(nmb->header.nm_flags.bcast), second_ip_buf ));
381 return send_netbios_packet( packet );
384 /***************************************************************************
385 Sends out a name refresh.
386 **************************************************************************/
388 static bool initiate_name_refresh_packet( struct packet_struct *packet,
389 uint16 nb_flags, struct in_addr *refresh_ip)
391 struct nmb_packet *nmb = &packet->packet.nmb;
393 nmb->header.opcode = NMB_NAME_REFRESH_OPCODE_8;
394 nmb->header.arcount = 1;
396 nmb->header.nm_flags.recursion_desired = False;
398 if(create_and_init_additional_record(packet, nb_flags, refresh_ip) == False)
399 return False;
401 DEBUG(4,("initiate_name_refresh_packet: sending refresh for name %s (bcast=%s) to IP %s\n",
402 nmb_namestr(&nmb->additional->rr_name),
403 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
405 return send_netbios_packet( packet );
408 /***************************************************************************
409 Sends out a name release.
410 **************************************************************************/
412 static bool initiate_name_release_packet( struct packet_struct *packet,
413 uint16 nb_flags, struct in_addr *release_ip)
415 struct nmb_packet *nmb = &packet->packet.nmb;
417 nmb->header.opcode = NMB_NAME_RELEASE_OPCODE;
418 nmb->header.arcount = 1;
420 nmb->header.nm_flags.recursion_desired = False;
422 if(create_and_init_additional_record(packet, nb_flags, release_ip) == False)
423 return False;
425 DEBUG(4,("initiate_name_release_packet: sending release for name %s (bcast=%s) to IP %s\n",
426 nmb_namestr(&nmb->additional->rr_name),
427 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
429 return send_netbios_packet( packet );
432 /***************************************************************************
433 Sends out a node status.
434 **************************************************************************/
436 static bool initiate_node_status_packet( struct packet_struct *packet )
438 struct nmb_packet *nmb = &packet->packet.nmb;
440 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
441 nmb->header.arcount = 0;
443 nmb->header.nm_flags.recursion_desired = False;
445 nmb->question.question_type = QUESTION_TYPE_NB_STATUS;
447 DEBUG(4,("initiate_node_status_packet: sending node status request for name %s to IP %s\n",
448 nmb_namestr(&nmb->question.question_name),
449 inet_ntoa(packet->ip)));
451 return send_netbios_packet( packet );
454 /****************************************************************************
455 Simplification functions for queuing standard packets.
456 These should be the only publicly callable functions for sending
457 out packets.
458 ****************************************************************************/
460 /****************************************************************************
461 Assertion - we should never be sending nmbd packets on the remote
462 broadcast subnet.
463 ****************************************************************************/
465 static bool assert_check_subnet(struct subnet_record *subrec)
467 if( subrec == remote_broadcast_subnet) {
468 DEBUG(0,("assert_check_subnet: Attempt to send packet on remote broadcast subnet. \
469 This is a bug.\n"));
470 return True;
472 return False;
475 /****************************************************************************
476 Queue a register name packet to the broadcast address of a subnet.
477 ****************************************************************************/
479 struct response_record *queue_register_name( struct subnet_record *subrec,
480 response_function resp_fn,
481 timeout_response_function timeout_fn,
482 register_name_success_function success_fn,
483 register_name_fail_function fail_fn,
484 struct userdata_struct *userdata,
485 struct nmb_name *nmbname,
486 uint16 nb_flags)
488 struct packet_struct *p;
489 struct response_record *rrec;
490 struct sockaddr_storage ss;
491 const struct sockaddr_storage *pss = NULL;
492 if(assert_check_subnet(subrec))
493 return NULL;
495 /* note that all name registration requests have RD set (rfc1002 - section 4.2.2 */
496 if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), True,
497 subrec->bcast_ip)) == NULL)
498 return NULL;
500 in_addr_to_sockaddr_storage(&ss, subrec->bcast_ip);
501 pss = iface_ip((struct sockaddr *)(void *)&ss);
502 if (!pss || pss->ss_family != AF_INET) {
503 p->locked = False;
504 free_packet(p);
505 return NULL;
508 if(initiate_name_register_packet(p, nb_flags,
509 &((const struct sockaddr_in *)pss)->sin_addr) == False) {
510 p->locked = False;
511 free_packet(p);
512 return NULL;
515 if((rrec = make_response_record(subrec, /* subnet record. */
516 p, /* packet we sent. */
517 resp_fn, /* function to call on response. */
518 timeout_fn, /* function to call on timeout. */
519 (success_function)success_fn, /* function to call on operation success. */
520 (fail_function)fail_fn, /* function to call on operation fail. */
521 userdata)) == NULL) {
522 p->locked = False;
523 free_packet(p);
524 return NULL;
527 return rrec;
530 /****************************************************************************
531 Queue a refresh name packet to the broadcast address of a subnet.
532 ****************************************************************************/
534 void queue_wins_refresh(struct nmb_name *nmbname,
535 response_function resp_fn,
536 timeout_response_function timeout_fn,
537 uint16 nb_flags,
538 struct in_addr refresh_ip,
539 const char *tag)
541 struct packet_struct *p;
542 struct response_record *rrec;
543 struct in_addr wins_ip;
544 struct userdata_struct *userdata;
545 fstring ip_str;
547 wins_ip = wins_srv_ip_tag(tag, refresh_ip);
549 if ((p = create_and_init_netbios_packet(nmbname, False, False, wins_ip)) == NULL) {
550 return;
553 if (!initiate_name_refresh_packet(p, nb_flags, &refresh_ip)) {
554 p->locked = False;
555 free_packet(p);
556 return;
559 fstrcpy(ip_str, inet_ntoa(refresh_ip));
561 DEBUG(6,("Refreshing name %s IP %s with WINS server %s using tag '%s'\n",
562 nmb_namestr(nmbname), ip_str, inet_ntoa(wins_ip), tag));
564 userdata = (struct userdata_struct *)SMB_MALLOC(sizeof(*userdata) + strlen(tag) + 1);
565 if (!userdata) {
566 p->locked = False;
567 free_packet(p);
568 DEBUG(0,("Failed to allocate userdata structure!\n"));
569 return;
571 ZERO_STRUCTP(userdata);
572 userdata->userdata_len = strlen(tag) + 1;
573 strlcpy(userdata->data, tag, userdata->userdata_len);
575 if ((rrec = make_response_record(unicast_subnet,
577 resp_fn, timeout_fn,
578 NULL,
579 NULL,
580 userdata)) == NULL) {
581 p->locked = False;
582 free_packet(p);
583 return;
586 free(userdata);
588 /* we don't want to repeat refresh packets */
589 rrec->repeat_count = 0;
593 /****************************************************************************
594 Queue a multihomed register name packet to a given WINS server IP
595 ****************************************************************************/
597 struct response_record *queue_register_multihomed_name( struct subnet_record *subrec,
598 response_function resp_fn,
599 timeout_response_function timeout_fn,
600 register_name_success_function success_fn,
601 register_name_fail_function fail_fn,
602 struct userdata_struct *userdata,
603 struct nmb_name *nmbname,
604 uint16 nb_flags,
605 struct in_addr register_ip,
606 struct in_addr wins_ip)
608 struct packet_struct *p;
609 struct response_record *rrec;
610 bool ret;
612 /* Sanity check. */
613 if(subrec != unicast_subnet) {
614 DEBUG(0,("queue_register_multihomed_name: should only be done on \
615 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
616 return NULL;
619 if(assert_check_subnet(subrec))
620 return NULL;
622 if ((p = create_and_init_netbios_packet(nmbname, False, True, wins_ip)) == NULL)
623 return NULL;
625 if (nb_flags & NB_GROUP)
626 ret = initiate_name_register_packet( p, nb_flags, &register_ip);
627 else
628 ret = initiate_multihomed_name_register_packet(p, nb_flags, &register_ip);
630 if (ret == False) {
631 p->locked = False;
632 free_packet(p);
633 return NULL;
636 if ((rrec = make_response_record(subrec, /* subnet record. */
637 p, /* packet we sent. */
638 resp_fn, /* function to call on response. */
639 timeout_fn, /* function to call on timeout. */
640 (success_function)success_fn, /* function to call on operation success. */
641 (fail_function)fail_fn, /* function to call on operation fail. */
642 userdata)) == NULL) {
643 p->locked = False;
644 free_packet(p);
645 return NULL;
648 return rrec;
651 /****************************************************************************
652 Queue a release name packet to the broadcast address of a subnet.
653 ****************************************************************************/
655 struct response_record *queue_release_name( struct subnet_record *subrec,
656 response_function resp_fn,
657 timeout_response_function timeout_fn,
658 release_name_success_function success_fn,
659 release_name_fail_function fail_fn,
660 struct userdata_struct *userdata,
661 struct nmb_name *nmbname,
662 uint16 nb_flags,
663 struct in_addr release_ip,
664 struct in_addr dest_ip)
666 struct packet_struct *p;
667 struct response_record *rrec;
669 if(assert_check_subnet(subrec))
670 return NULL;
672 if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), False, dest_ip)) == NULL)
673 return NULL;
675 if(initiate_name_release_packet( p, nb_flags, &release_ip) == False) {
676 p->locked = False;
677 free_packet(p);
678 return NULL;
681 if((rrec = make_response_record(subrec, /* subnet record. */
682 p, /* packet we sent. */
683 resp_fn, /* function to call on response. */
684 timeout_fn, /* function to call on timeout. */
685 (success_function)success_fn, /* function to call on operation success. */
686 (fail_function)fail_fn, /* function to call on operation fail. */
687 userdata)) == NULL) {
688 p->locked = False;
689 free_packet(p);
690 return NULL;
694 * For a broadcast release packet, only send once.
695 * This will cause us to remove the name asap. JRA.
698 if (subrec != unicast_subnet) {
699 rrec->repeat_count = 0;
700 rrec->repeat_time = 0;
703 return rrec;
706 /****************************************************************************
707 Queue a query name packet to the broadcast address of a subnet.
708 ****************************************************************************/
710 struct response_record *queue_query_name( struct subnet_record *subrec,
711 response_function resp_fn,
712 timeout_response_function timeout_fn,
713 query_name_success_function success_fn,
714 query_name_fail_function fail_fn,
715 struct userdata_struct *userdata,
716 struct nmb_name *nmbname)
718 struct packet_struct *p;
719 struct response_record *rrec;
720 struct in_addr to_ip;
722 if(assert_check_subnet(subrec))
723 return NULL;
725 to_ip = subrec->bcast_ip;
727 /* queries to the WINS server turn up here as queries to IP 0.0.0.0
728 These need to be handled a bit differently */
729 if (subrec->type == UNICAST_SUBNET && is_zero_ip_v4(to_ip)) {
730 /* What we really need to do is loop over each of our wins
731 * servers and wins server tags here, but that just doesn't
732 * fit our architecture at the moment (userdata may already
733 * be used when we get here). For now we just query the first
734 * active wins server on the first tag.
736 char **tags = wins_srv_tags();
737 if (!tags) {
738 return NULL;
740 to_ip = wins_srv_ip_tag(tags[0], to_ip);
741 wins_srv_tags_free(tags);
744 if(( p = create_and_init_netbios_packet(nmbname,
745 (subrec != unicast_subnet),
746 (subrec == unicast_subnet),
747 to_ip)) == NULL)
748 return NULL;
750 if(lp_bind_interfaces_only()) {
751 int i;
753 DEBUG(10,("queue_query_name: bind_interfaces_only is set, looking for suitable source IP\n"));
754 for(i = 0; i < iface_count(); i++) {
755 const struct in_addr *ifip = iface_n_ip_v4(i);
757 if (ifip == NULL) {
758 DEBUG(0,("queue_query_name: interface %d has NULL IP address !\n", i));
759 continue;
762 if (is_loopback_ip_v4(*ifip)) {
763 DEBUG(5,("queue_query_name: ignoring loopback interface (%d)\n", i));
764 continue;
767 DEBUG(10,("queue_query_name: using source IP %s\n",inet_ntoa(*ifip)));
768 p->send_fd = find_subnet_fd_for_address( *ifip );
769 break;
773 if(initiate_name_query_packet( p ) == False) {
774 p->locked = False;
775 free_packet(p);
776 return NULL;
779 if((rrec = make_response_record(subrec, /* subnet record. */
780 p, /* packet we sent. */
781 resp_fn, /* function to call on response. */
782 timeout_fn, /* function to call on timeout. */
783 (success_function)success_fn, /* function to call on operation success. */
784 (fail_function)fail_fn, /* function to call on operation fail. */
785 userdata)) == NULL) {
786 p->locked = False;
787 free_packet(p);
788 return NULL;
791 return rrec;
794 /****************************************************************************
795 Queue a query name packet to a given address from the WINS subnet.
796 ****************************************************************************/
798 struct response_record *queue_query_name_from_wins_server( struct in_addr to_ip,
799 response_function resp_fn,
800 timeout_response_function timeout_fn,
801 query_name_success_function success_fn,
802 query_name_fail_function fail_fn,
803 struct userdata_struct *userdata,
804 struct nmb_name *nmbname)
806 struct packet_struct *p;
807 struct response_record *rrec;
809 if ((p = create_and_init_netbios_packet(nmbname, False, False, to_ip)) == NULL)
810 return NULL;
812 if(initiate_name_query_packet_from_wins_server( p ) == False) {
813 p->locked = False;
814 free_packet(p);
815 return NULL;
818 if((rrec = make_response_record(wins_server_subnet, /* subnet record. */
819 p, /* packet we sent. */
820 resp_fn, /* function to call on response. */
821 timeout_fn, /* function to call on timeout. */
822 (success_function)success_fn, /* function to call on operation success. */
823 (fail_function)fail_fn, /* function to call on operation fail. */
824 userdata)) == NULL) {
825 p->locked = False;
826 free_packet(p);
827 return NULL;
830 return rrec;
833 /****************************************************************************
834 Queue a node status packet to a given name and address.
835 ****************************************************************************/
837 struct response_record *queue_node_status( struct subnet_record *subrec,
838 response_function resp_fn,
839 timeout_response_function timeout_fn,
840 node_status_success_function success_fn,
841 node_status_fail_function fail_fn,
842 struct userdata_struct *userdata,
843 struct nmb_name *nmbname,
844 struct in_addr send_ip)
846 struct packet_struct *p;
847 struct response_record *rrec;
849 /* Sanity check. */
850 if(subrec != unicast_subnet) {
851 DEBUG(0,("queue_register_multihomed_name: should only be done on \
852 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
853 return NULL;
856 if(assert_check_subnet(subrec))
857 return NULL;
859 if(( p = create_and_init_netbios_packet(nmbname, False, False, send_ip)) == NULL)
860 return NULL;
862 if(initiate_node_status_packet(p) == False) {
863 p->locked = False;
864 free_packet(p);
865 return NULL;
868 if((rrec = make_response_record(subrec, /* subnet record. */
869 p, /* packet we sent. */
870 resp_fn, /* function to call on response. */
871 timeout_fn, /* function to call on timeout. */
872 (success_function)success_fn, /* function to call on operation success. */
873 (fail_function)fail_fn, /* function to call on operation fail. */
874 userdata)) == NULL) {
875 p->locked = False;
876 free_packet(p);
877 return NULL;
880 return rrec;
883 /****************************************************************************
884 Reply to a netbios name packet. see rfc1002.txt
885 ****************************************************************************/
887 void reply_netbios_packet(struct packet_struct *orig_packet,
888 int rcode, enum netbios_reply_type_code rcv_code, int opcode,
889 int ttl, char *data,int len)
891 struct packet_struct packet;
892 struct nmb_packet *nmb = NULL;
893 struct res_rec answers;
894 struct nmb_packet *orig_nmb = &orig_packet->packet.nmb;
895 bool loopback_this_packet = False;
896 int rr_type = RR_TYPE_NB;
897 const char *packet_type = "unknown";
899 /* Check if we are sending to or from ourselves. */
900 if(ismyip_v4(orig_packet->ip) && (orig_packet->port == global_nmb_port))
901 loopback_this_packet = True;
903 nmb = &packet.packet.nmb;
905 /* Do a partial copy of the packet. We clear the locked flag and
906 the resource record pointers. */
907 packet = *orig_packet; /* Full structure copy. */
908 packet.locked = False;
909 nmb->answers = NULL;
910 nmb->nsrecs = NULL;
911 nmb->additional = NULL;
913 switch (rcv_code) {
914 case NMB_STATUS:
915 packet_type = "nmb_status";
916 nmb->header.nm_flags.recursion_desired = False;
917 nmb->header.nm_flags.recursion_available = False;
918 rr_type = RR_TYPE_NBSTAT;
919 break;
920 case NMB_QUERY:
921 packet_type = "nmb_query";
922 nmb->header.nm_flags.recursion_desired = True;
923 nmb->header.nm_flags.recursion_available = True;
924 if (rcode) {
925 rr_type = RR_TYPE_NULL;
927 break;
928 case NMB_REG:
929 case NMB_REG_REFRESH:
930 packet_type = "nmb_reg";
931 nmb->header.nm_flags.recursion_desired = True;
932 nmb->header.nm_flags.recursion_available = True;
933 break;
934 case NMB_REL:
935 packet_type = "nmb_rel";
936 nmb->header.nm_flags.recursion_desired = False;
937 nmb->header.nm_flags.recursion_available = False;
938 break;
939 case NMB_WAIT_ACK:
940 packet_type = "nmb_wack";
941 nmb->header.nm_flags.recursion_desired = False;
942 nmb->header.nm_flags.recursion_available = False;
943 rr_type = RR_TYPE_NULL;
944 break;
945 case WINS_REG:
946 packet_type = "wins_reg";
947 nmb->header.nm_flags.recursion_desired = True;
948 nmb->header.nm_flags.recursion_available = True;
949 break;
950 case WINS_QUERY:
951 packet_type = "wins_query";
952 nmb->header.nm_flags.recursion_desired = True;
953 nmb->header.nm_flags.recursion_available = True;
954 if (rcode) {
955 rr_type = RR_TYPE_NULL;
957 break;
958 default:
959 DEBUG(0,("reply_netbios_packet: Unknown packet type: %s %s to ip %s\n",
960 packet_type, nmb_namestr(&orig_nmb->question.question_name),
961 inet_ntoa(packet.ip)));
962 return;
965 DEBUG(4,("reply_netbios_packet: sending a reply of packet type: %s %s to ip %s \
966 for id %hu\n", packet_type, nmb_namestr(&orig_nmb->question.question_name),
967 inet_ntoa(packet.ip), orig_nmb->header.name_trn_id));
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;
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;
982 memset((char*)&nmb->question,'\0',sizeof(nmb->question));
984 nmb->answers = &answers;
985 memset((char*)nmb->answers,'\0',sizeof(*nmb->answers));
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;
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;
999 nmb->answers->rdlength = len;
1000 memcpy(nmb->answers->rdata, data, len);
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;
1012 packet.timestamp = time(NULL);
1014 debug_nmb_packet(&packet);
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));
1028 /*******************************************************************
1029 Queue a packet into a packet queue
1030 ******************************************************************/
1032 void queue_packet(struct packet_struct *packet)
1034 DLIST_ADD_END(packet_queue, packet, struct packet_struct *);
1037 /****************************************************************************
1038 Try and find a matching subnet record for a datagram port 138 packet.
1039 ****************************************************************************/
1041 static struct subnet_record *find_subnet_for_dgram_browse_packet(struct packet_struct *p)
1043 struct subnet_record *subrec;
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;
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...
1058 return FIRST_SUBNET;
1061 /****************************************************************************
1062 Dispatch a browse frame from port 138 to the correct processing function.
1063 ****************************************************************************/
1065 static void process_browse_packet(struct packet_struct *p, char *buf,int len)
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;
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, global_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, global_scope()));
1078 return;
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;
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;
1127 debug_browse_data(buf, len);
1128 process_master_browser_announce(subrec, p, buf+1);
1129 break;
1130 case ANN_BecomeBackup:
1132 * We don't currently implement this. Log it just in case.
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;
1148 /****************************************************************************
1149 Dispatch a LanMan browse frame from port 138 to the correct processing function.
1150 ****************************************************************************/
1152 static void process_lanman_packet(struct packet_struct *p, char *buf,int len)
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;
1160 /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1162 pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1163 if (!strequal(scope, global_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, global_scope()));
1166 return;
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;
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;
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 ****************************************************************************/
1198 static bool listening(struct packet_struct *p,struct nmb_name *nbname)
1200 struct subnet_record *subrec = NULL;
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;
1207 if(subrec == NULL)
1208 subrec = unicast_subnet;
1210 return (find_name_on_subnet(subrec, nbname, FIND_SELF_NAME) != NULL);
1213 /****************************************************************************
1214 Process udp 138 datagrams
1215 ****************************************************************************/
1217 static void process_dgram(struct packet_struct *p)
1219 char *buf;
1220 char *buf2;
1221 int len;
1222 struct dgram_packet *dgram = &p->packet.dgram;
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;
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;
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;
1250 buf = &dgram->data[0];
1251 buf -= 4; /* XXXX for the pseudo tcp length - someday I need to get rid of this */
1253 if (CVAL(buf,smb_com) != SMBtrans)
1254 return;
1256 len = SVAL(buf,smb_vwv11);
1257 buf2 = smb_base(buf) + SVAL(buf,smb_vwv12);
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;
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;
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;
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(buf),CVAL(buf2,0),len));
1295 /* Datagram packet received for the browser mailslot */
1296 if (strequal(smb_buf(buf),BROWSE_MAILSLOT)) {
1297 process_browse_packet(p,buf2,len);
1298 return;
1301 /* Datagram packet received for the LAN Manager mailslot */
1302 if (strequal(smb_buf(buf),LANMAN_MAILSLOT)) {
1303 process_lanman_packet(p,buf2,len);
1304 return;
1307 /* Datagram packet received for the domain logon mailslot */
1308 if (strequal(smb_buf(buf),NET_LOGON_MAILSLOT)) {
1309 process_logon_packet(p,buf2,len,NET_LOGON_MAILSLOT);
1310 return;
1313 /* Datagram packet received for the NT domain logon mailslot */
1314 if (strequal(smb_buf(buf),NT_LOGON_MAILSLOT)) {
1315 process_logon_packet(p,buf2,len,NT_LOGON_MAILSLOT);
1316 return;
1319 nb_packet_dispatch(packet_server, p);
1322 /****************************************************************************
1323 Validate a response nmb packet.
1324 ****************************************************************************/
1326 static bool validate_nmb_response_packet( struct nmb_packet *nmb )
1328 bool ignore = False;
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;
1338 break;
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;
1345 break;
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;
1352 break;
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;
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;
1367 if(ignore)
1368 DEBUG(0,("Ignoring response packet with opcode %d.\n", nmb->header.opcode));
1370 return ignore;
1373 /****************************************************************************
1374 Validate a request nmb packet.
1375 ****************************************************************************/
1377 static bool validate_nmb_packet( struct nmb_packet *nmb )
1379 bool ignore = False;
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;
1390 break;
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;
1398 break;
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;
1405 break;
1406 default:
1407 DEBUG(0,("validate_nmb_packet: Ignoring packet with unknown opcode %d.\n",
1408 nmb->header.opcode));
1409 return True;
1412 if(ignore)
1413 DEBUG(0,("validate_nmb_packet: Ignoring request packet with opcode %d.\n", nmb->header.opcode));
1415 return ignore;
1418 /****************************************************************************
1419 Find a subnet (and potentially a response record) for a packet.
1420 ****************************************************************************/
1422 static struct subnet_record *find_subnet_for_nmb_packet( struct packet_struct *p,
1423 struct response_record **pprrec)
1425 struct nmb_packet *nmb = &p->packet.nmb;
1426 struct response_record *rrec = NULL;
1427 struct subnet_record *subrec = NULL;
1429 if(pprrec != NULL)
1430 *pprrec = NULL;
1432 if(nmb->header.response) {
1433 /* It's a response packet. Find a record for it or it's an error. */
1435 rrec = find_response_record( &subrec, nmb->header.name_trn_id);
1436 if(rrec == NULL) {
1437 DEBUG(3,("find_subnet_for_nmb_packet: response record not found for response id %hu\n",
1438 nmb->header.name_trn_id));
1439 nb_packet_dispatch(packet_server, p);
1440 return NULL;
1443 if(subrec == NULL) {
1444 DEBUG(0,("find_subnet_for_nmb_packet: subnet record not found for response id %hu\n",
1445 nmb->header.name_trn_id));
1446 return NULL;
1449 if(pprrec != NULL)
1450 *pprrec = rrec;
1451 return subrec;
1454 /* Try and see what subnet this packet belongs to. */
1456 /* WINS server ? */
1457 if(packet_is_for_wins_server(p))
1458 return wins_server_subnet;
1460 /* If it wasn't a broadcast packet then send to the UNICAST subnet. */
1461 if(nmb->header.nm_flags.bcast == False)
1462 return unicast_subnet;
1464 /* Go through all the broadcast subnets and see if the mask matches. */
1465 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1466 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1467 return subrec;
1470 /* If none match it must have been a directed broadcast - assign the remote_broadcast_subnet. */
1471 return remote_broadcast_subnet;
1474 /****************************************************************************
1475 Process a nmb request packet - validate the packet and route it.
1476 ****************************************************************************/
1478 static void process_nmb_request(struct packet_struct *p)
1480 struct nmb_packet *nmb = &p->packet.nmb;
1481 struct subnet_record *subrec = NULL;
1483 debug_nmb_packet(p);
1485 /* Ensure we have a good packet. */
1486 if(validate_nmb_packet(nmb))
1487 return;
1489 /* Allocate a subnet to this packet - if we cannot - fail. */
1490 if((subrec = find_subnet_for_nmb_packet(p, NULL))==NULL)
1491 return;
1493 switch (nmb->header.opcode) {
1494 case NMB_NAME_REG_OPCODE:
1495 if(subrec == wins_server_subnet)
1496 wins_process_name_registration_request(subrec, p);
1497 else
1498 process_name_registration_request(subrec, p);
1499 break;
1501 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1502 case NMB_NAME_REFRESH_OPCODE_9:
1503 if(subrec == wins_server_subnet)
1504 wins_process_name_refresh_request(subrec, p);
1505 else
1506 process_name_refresh_request(subrec, p);
1507 break;
1509 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1510 if(subrec == wins_server_subnet) {
1511 wins_process_multihomed_name_registration_request(subrec, p);
1512 } else {
1513 DEBUG(0,("process_nmb_request: Multihomed registration request must be \
1514 directed at a WINS server.\n"));
1516 break;
1518 case NMB_NAME_QUERY_OPCODE:
1519 switch (nmb->question.question_type) {
1520 case QUESTION_TYPE_NB_QUERY:
1521 if(subrec == wins_server_subnet)
1522 wins_process_name_query_request(subrec, p);
1523 else
1524 process_name_query_request(subrec, p);
1525 break;
1526 case QUESTION_TYPE_NB_STATUS:
1527 if(subrec == wins_server_subnet) {
1528 DEBUG(0,("process_nmb_request: NB_STATUS request directed at WINS server is \
1529 not allowed.\n"));
1530 break;
1531 } else {
1532 process_node_status_request(subrec, p);
1534 break;
1536 break;
1538 case NMB_NAME_RELEASE_OPCODE:
1539 if(subrec == wins_server_subnet)
1540 wins_process_name_release_request(subrec, p);
1541 else
1542 process_name_release_request(subrec, p);
1543 break;
1547 /****************************************************************************
1548 Process a nmb response packet - validate the packet and route it.
1549 to either the WINS server or a normal response.
1550 ****************************************************************************/
1552 static void process_nmb_response(struct packet_struct *p)
1554 struct nmb_packet *nmb = &p->packet.nmb;
1555 struct subnet_record *subrec = NULL;
1556 struct response_record *rrec = NULL;
1558 debug_nmb_packet(p);
1560 if(validate_nmb_response_packet(nmb))
1561 return;
1563 if((subrec = find_subnet_for_nmb_packet(p, &rrec))==NULL)
1564 return;
1566 if(rrec == NULL) {
1567 DEBUG(0,("process_nmb_response: response packet received but no response record \
1568 found for id = %hu. Ignoring packet.\n", nmb->header.name_trn_id));
1569 return;
1572 /* Increment the number of responses received for this record. */
1573 rrec->num_msgs++;
1574 /* Ensure we don't re-send the request. */
1575 rrec->repeat_count = 0;
1577 /* Call the response received function for this packet. */
1578 (*rrec->resp_fn)(subrec, rrec, p);
1581 /*******************************************************************
1582 Run elements off the packet queue till its empty
1583 ******************************************************************/
1585 void run_packet_queue(void)
1587 struct packet_struct *p;
1589 while ((p = packet_queue)) {
1590 DLIST_REMOVE(packet_queue, p);
1592 switch (p->packet_type) {
1593 case NMB_PACKET:
1594 if(p->packet.nmb.header.response)
1595 process_nmb_response(p);
1596 else
1597 process_nmb_request(p);
1598 break;
1600 case DGRAM_PACKET:
1601 process_dgram(p);
1602 break;
1604 free_packet(p);
1608 /*******************************************************************
1609 Retransmit or timeout elements from all the outgoing subnet response
1610 record queues. NOTE that this code must also check the WINS server
1611 subnet for response records to timeout as the WINS server code
1612 can send requests to check if a client still owns a name.
1613 (Patch from Andrey Alekseyev <fetch@muffin.arcadia.spb.ru>).
1614 ******************************************************************/
1616 void retransmit_or_expire_response_records(time_t t)
1618 struct subnet_record *subrec;
1620 for (subrec = FIRST_SUBNET; subrec; subrec = get_next_subnet_maybe_unicast_or_wins_server(subrec)) {
1621 struct response_record *rrec, *nextrrec;
1623 restart:
1625 for (rrec = subrec->responselist; rrec; rrec = nextrrec) {
1626 nextrrec = rrec->next;
1628 if (rrec->repeat_time <= t) {
1629 if (rrec->repeat_count > 0) {
1630 /* Resend while we have a non-zero repeat_count. */
1631 if(!send_packet(rrec->packet)) {
1632 DEBUG(0,("retransmit_or_expire_response_records: Failed to resend packet id %hu \
1633 to IP %s on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1635 rrec->repeat_time = t + rrec->repeat_interval;
1636 rrec->repeat_count--;
1637 } else {
1638 DEBUG(4,("retransmit_or_expire_response_records: timeout for packet id %hu to IP %s \
1639 on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1642 * Check the flag in this record to prevent recursion if we end
1643 * up in this function again via the timeout function call.
1646 if(!rrec->in_expiration_processing) {
1649 * Set the recursion protection flag in this record.
1652 rrec->in_expiration_processing = True;
1654 /* Call the timeout function. This will deal with removing the
1655 timed out packet. */
1656 if(rrec->timeout_fn) {
1657 (*rrec->timeout_fn)(subrec, rrec);
1658 } else {
1659 /* We must remove the record ourself if there is
1660 no timeout function. */
1661 remove_response_record(subrec, rrec);
1663 /* We have changed subrec->responselist,
1664 * restart from the beginning of this list. */
1665 goto restart;
1666 } /* !rrec->in_expitation_processing */
1667 } /* rrec->repeat_count > 0 */
1668 } /* rrec->repeat_time <= t */
1669 } /* end for rrec */
1670 } /* end for subnet */
1673 /****************************************************************************
1674 Create an fd_set containing all the sockets in the subnet structures,
1675 plus the broadcast sockets.
1676 ***************************************************************************/
1678 struct socket_attributes {
1679 enum packet_type type;
1680 bool broadcast;
1683 static bool create_listen_pollfds(struct pollfd **pfds,
1684 struct socket_attributes **pattrs,
1685 int *pnum_sockets)
1687 struct subnet_record *subrec = NULL;
1688 int count = 0;
1689 int num = 0;
1690 struct pollfd *fds;
1691 struct socket_attributes *attrs;
1693 /* The ClientNMB and ClientDGRAM sockets */
1694 count = 2;
1696 /* Check that we can add all the fd's we need. */
1697 for (subrec = FIRST_SUBNET;
1698 subrec != NULL;
1699 subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1700 count += 2; /* nmb_sock and dgram_sock */
1701 if (subrec->nmb_bcast != -1) {
1702 count += 1;
1704 if (subrec->dgram_bcast != -1) {
1705 count += 1;
1709 fds = TALLOC_ZERO_ARRAY(NULL, struct pollfd, count);
1710 if (fds == NULL) {
1711 DEBUG(1, ("create_listen_pollfds: malloc fail for fds. "
1712 "size %d\n", count));
1713 return true;
1716 attrs = TALLOC_ARRAY(NULL, struct socket_attributes, count);
1717 if (fds == NULL) {
1718 DEBUG(1, ("create_listen_pollfds: malloc fail for attrs. "
1719 "size %d\n", count));
1720 SAFE_FREE(fds);
1721 return true;
1724 num = 0;
1726 fds[num].fd = ClientNMB;
1727 attrs[num].type = NMB_PACKET;
1728 attrs[num].broadcast = false;
1729 num += 1;
1731 fds[num].fd = ClientDGRAM;
1732 attrs[num].type = DGRAM_PACKET;
1733 attrs[num].broadcast = false;
1734 num += 1;
1736 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1738 fds[num].fd = subrec->nmb_sock;
1739 attrs[num].type = NMB_PACKET;
1740 attrs[num].broadcast = false;
1741 num += 1;
1743 if (subrec->nmb_bcast != -1) {
1744 fds[num].fd = subrec->nmb_bcast;
1745 attrs[num].type = NMB_PACKET;
1746 attrs[num].broadcast = true;
1747 num += 1;
1750 fds[num].fd = subrec->dgram_sock;
1751 attrs[num].type = DGRAM_PACKET;
1752 attrs[num].broadcast = false;
1753 num += 1;
1755 if (subrec->dgram_bcast != -1) {
1756 fds[num].fd = subrec->dgram_bcast;
1757 attrs[num].type = DGRAM_PACKET;
1758 attrs[num].broadcast = true;
1759 num += 1;
1763 TALLOC_FREE(*pfds);
1764 *pfds = fds;
1766 TALLOC_FREE(*pattrs);
1767 *pattrs = attrs;
1769 *pnum_sockets = count;
1771 return False;
1774 /****************************************************************************
1775 List of packets we're processing this select.
1776 ***************************************************************************/
1778 struct processed_packet {
1779 struct processed_packet *next;
1780 struct processed_packet *prev;
1781 enum packet_type packet_type;
1782 struct in_addr ip;
1783 int packet_id;
1786 /****************************************************************************
1787 Have we seen this before ?
1788 ***************************************************************************/
1790 static bool is_processed_packet(struct processed_packet *processed_packet_list,
1791 struct packet_struct *packet)
1793 struct processed_packet *p = NULL;
1795 for (p = processed_packet_list; p; p = p->next) {
1796 if (ip_equal_v4(p->ip, packet->ip) && p->packet_type == packet->packet_type) {
1797 if ((p->packet_type == NMB_PACKET) &&
1798 (p->packet_id ==
1799 packet->packet.nmb.header.name_trn_id)) {
1800 return true;
1801 } else if ((p->packet_type == DGRAM_PACKET) &&
1802 (p->packet_id ==
1803 packet->packet.dgram.header.dgm_id)) {
1804 return true;
1808 return false;
1811 /****************************************************************************
1812 Keep a list of what we've seen before.
1813 ***************************************************************************/
1815 static bool store_processed_packet(struct processed_packet **pp_processed_packet_list,
1816 struct packet_struct *packet)
1818 struct processed_packet *p = SMB_MALLOC_P(struct processed_packet);
1819 if (!p) {
1820 return false;
1822 p->packet_type = packet->packet_type;
1823 p->ip = packet->ip;
1824 if (packet->packet_type == NMB_PACKET) {
1825 p->packet_id = packet->packet.nmb.header.name_trn_id;
1826 } else if (packet->packet_type == DGRAM_PACKET) {
1827 p->packet_id = packet->packet.dgram.header.dgm_id;
1828 } else {
1829 SAFE_FREE(p);
1830 return false;
1833 DLIST_ADD(*pp_processed_packet_list, p);
1834 return true;
1837 /****************************************************************************
1838 Throw away what we've seen before.
1839 ***************************************************************************/
1841 static void free_processed_packet_list(struct processed_packet **pp_processed_packet_list)
1843 struct processed_packet *p = NULL, *next = NULL;
1845 for (p = *pp_processed_packet_list; p; p = next) {
1846 next = p->next;
1847 DLIST_REMOVE(*pp_processed_packet_list, p);
1848 SAFE_FREE(p);
1852 /****************************************************************************
1853 Listens for NMB or DGRAM packets, and queues them.
1854 return True if the socket is dead
1855 ***************************************************************************/
1857 bool listen_for_packets(bool run_election)
1859 static struct pollfd *fds = NULL;
1860 static struct socket_attributes *attrs = NULL;
1861 static int listen_number = 0;
1862 int num_sockets;
1863 int i;
1865 int pollrtn;
1866 int timeout;
1867 #ifndef SYNC_DNS
1868 int dns_fd;
1869 int dns_pollidx = -1;
1870 #endif
1871 struct processed_packet *processed_packet_list = NULL;
1873 if ((fds == NULL) || rescan_listen_set) {
1874 if (create_listen_pollfds(&fds, &attrs, &listen_number)) {
1875 DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
1876 return True;
1878 rescan_listen_set = False;
1882 * "fds" can be enlarged by event_add_to_poll_args
1883 * below. Shrink it again to what was given to us by
1884 * create_listen_pollfds.
1887 fds = TALLOC_REALLOC_ARRAY(NULL, fds, struct pollfd, listen_number);
1888 if (fds == NULL) {
1889 return true;
1891 num_sockets = listen_number;
1893 #ifndef SYNC_DNS
1894 dns_fd = asyncdns_fd();
1895 if (dns_fd != -1) {
1896 fds = TALLOC_REALLOC_ARRAY(NULL, fds, struct pollfd, num_sockets+1);
1897 if (fds == NULL) {
1898 return true;
1900 dns_pollidx = num_sockets;
1901 fds[num_sockets].fd = dns_fd;
1902 num_sockets += 1;
1904 #endif
1906 for (i=0; i<num_sockets; i++) {
1907 fds[i].events = POLLIN|POLLHUP;
1910 /* Process a signal and timer events now... */
1911 if (run_events_poll(nmbd_event_context(), 0, NULL, 0)) {
1912 return False;
1916 * During elections and when expecting a netbios response packet we
1917 * need to send election packets at tighter intervals.
1918 * Ideally it needs to be the interval (in ms) between time now and
1919 * the time we are expecting the next netbios packet.
1922 timeout = ((run_election||num_response_packets)
1923 ? 1 : NMBD_SELECT_LOOP) * 1000;
1925 event_add_to_poll_args(nmbd_event_context(), NULL,
1926 &fds, &num_sockets, &timeout);
1928 pollrtn = sys_poll(fds, num_sockets, timeout);
1930 if (run_events_poll(nmbd_event_context(), pollrtn, fds, num_sockets)) {
1931 return False;
1934 if (pollrtn == -1) {
1935 return False;
1938 #ifndef SYNC_DNS
1939 if ((dns_fd != -1) && (dns_pollidx != -1) &&
1940 (fds[dns_pollidx].revents & (POLLIN|POLLHUP|POLLERR))) {
1941 run_dns_queue();
1943 #endif
1945 for(i = 0; i < listen_number; i++) {
1946 enum packet_type packet_type;
1947 struct packet_struct *packet;
1948 const char *packet_name;
1949 int client_fd;
1950 int client_port;
1952 if ((fds[i].revents & (POLLIN|POLLHUP|POLLERR)) == 0) {
1953 continue;
1956 if (attrs[i].type == NMB_PACKET) {
1957 /* Port 137 */
1958 packet_type = NMB_PACKET;
1959 packet_name = "nmb";
1960 client_fd = ClientNMB;
1961 client_port = global_nmb_port;
1962 } else {
1963 /* Port 138 */
1964 packet_type = DGRAM_PACKET;
1965 packet_name = "dgram";
1966 client_fd = ClientDGRAM;
1967 client_port = DGRAM_PORT;
1970 packet = read_packet(fds[i].fd, packet_type);
1971 if (!packet) {
1972 continue;
1976 * If we got a packet on the broadcast socket and interfaces
1977 * only is set then check it came from one of our local nets.
1979 if (lp_bind_interfaces_only() &&
1980 (fds[i].fd == client_fd) &&
1981 (!is_local_net_v4(packet->ip))) {
1982 DEBUG(7,("discarding %s packet sent to broadcast socket from %s:%d\n",
1983 packet_name, inet_ntoa(packet->ip), packet->port));
1984 free_packet(packet);
1985 continue;
1988 if ((is_loopback_ip_v4(packet->ip) || ismyip_v4(packet->ip)) &&
1989 packet->port == client_port)
1991 if (client_port == DGRAM_PORT) {
1992 DEBUG(7,("discarding own dgram packet from %s:%d\n",
1993 inet_ntoa(packet->ip),packet->port));
1994 free_packet(packet);
1995 continue;
1998 if (packet->packet.nmb.header.nm_flags.bcast) {
1999 DEBUG(7,("discarding own nmb bcast packet from %s:%d\n",
2000 inet_ntoa(packet->ip),packet->port));
2001 free_packet(packet);
2002 continue;
2006 if (is_processed_packet(processed_packet_list, packet)) {
2007 DEBUG(7,("discarding duplicate packet from %s:%d\n",
2008 inet_ntoa(packet->ip),packet->port));
2009 free_packet(packet);
2010 continue;
2013 store_processed_packet(&processed_packet_list, packet);
2015 if (attrs[i].broadcast) {
2016 /* this is a broadcast socket */
2017 packet->send_fd = fds[i-1].fd;
2018 } else {
2019 /* this is already a unicast socket */
2020 packet->send_fd = fds[i].fd;
2023 queue_packet(packet);
2026 free_processed_packet_list(&processed_packet_list);
2027 return False;
2030 /****************************************************************************
2031 Construct and send a netbios DGRAM.
2032 **************************************************************************/
2034 bool send_mailslot(bool unique, const char *mailslot,char *buf, size_t len,
2035 const char *srcname, int src_type,
2036 const char *dstname, int dest_type,
2037 struct in_addr dest_ip,struct in_addr src_ip,
2038 int dest_port)
2040 bool loopback_this_packet = False;
2041 struct packet_struct p;
2042 struct dgram_packet *dgram = &p.packet.dgram;
2043 char *ptr,*p2;
2044 char tmp[4];
2046 memset((char *)&p,'\0',sizeof(p));
2048 if(ismyip_v4(dest_ip) && (dest_port == DGRAM_PORT)) /* Only if to DGRAM_PORT */
2049 loopback_this_packet = True;
2051 /* generate_name_trn_id(); */ /* Not used, so gone, RJS */
2053 /* DIRECT GROUP or UNIQUE datagram. */
2054 dgram->header.msg_type = unique ? 0x10 : 0x11;
2055 dgram->header.flags.node_type = M_NODE;
2056 dgram->header.flags.first = True;
2057 dgram->header.flags.more = False;
2058 dgram->header.dgm_id = generate_name_trn_id();
2059 dgram->header.source_ip = src_ip;
2060 dgram->header.source_port = DGRAM_PORT;
2061 dgram->header.dgm_length = 0; /* Let build_dgram() handle this. */
2062 dgram->header.packet_offset = 0;
2064 make_nmb_name(&dgram->source_name,srcname,src_type);
2065 make_nmb_name(&dgram->dest_name,dstname,dest_type);
2067 ptr = &dgram->data[0];
2069 /* Setup the smb part. */
2070 ptr -= 4; /* XXX Ugliness because of handling of tcp SMB length. */
2071 memcpy(tmp,ptr,4);
2073 if (smb_size + 17*2 + strlen(mailslot) + 1 + len > MAX_DGRAM_SIZE) {
2074 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
2075 return false;
2078 cli_set_message(ptr,17,strlen(mailslot) + 1 + len,True);
2079 memcpy(ptr,tmp,4);
2081 SCVAL(ptr,smb_com,SMBtrans);
2082 SSVAL(ptr,smb_vwv1,len);
2083 SSVAL(ptr,smb_vwv11,len);
2084 SSVAL(ptr,smb_vwv12,70 + strlen(mailslot));
2085 SSVAL(ptr,smb_vwv13,3);
2086 SSVAL(ptr,smb_vwv14,1);
2087 SSVAL(ptr,smb_vwv15,1);
2088 SSVAL(ptr,smb_vwv16,2);
2089 p2 = smb_buf(ptr);
2090 safe_strcpy_base(p2, mailslot, dgram->data, sizeof(dgram->data));
2091 p2 = skip_string(ptr,MAX_DGRAM_SIZE,p2);
2093 if (((p2+len) > dgram->data+sizeof(dgram->data)) || ((p2+len) < p2)) {
2094 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
2095 return False;
2096 } else {
2097 if (len) {
2098 memcpy(p2,buf,len);
2100 p2 += len;
2103 dgram->datasize = PTR_DIFF(p2,ptr+4); /* +4 for tcp length. */
2105 p.ip = dest_ip;
2106 p.port = dest_port;
2107 p.recv_fd = -1;
2108 p.send_fd = find_subnet_mailslot_fd_for_address( src_ip );
2109 p.timestamp = time(NULL);
2110 p.packet_type = DGRAM_PACKET;
2112 DEBUG(4,("send_mailslot: Sending to mailslot %s from %s IP %s ", mailslot,
2113 nmb_namestr(&dgram->source_name), inet_ntoa(src_ip)));
2114 DEBUG(4,("to %s IP %s\n", nmb_namestr(&dgram->dest_name), inet_ntoa(dest_ip)));
2116 debug_browse_data(buf, len);
2118 if(loopback_this_packet) {
2119 struct packet_struct *lo_packet = NULL;
2120 DEBUG(5,("send_mailslot: sending packet to ourselves.\n"));
2121 if((lo_packet = copy_packet(&p)) == NULL)
2122 return False;
2123 queue_packet(lo_packet);
2124 return True;
2125 } else {
2126 return(send_packet(&p));