s3-examples: make sure to match correct key name in adssearch.
[Samba/eduardoll.git] / source3 / nmbd / nmbd_packets.c
blobf69845b346c4b6c9586ba6cee76ba6a2bd150cfa
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/>.
23 #include "includes.h"
25 extern int ClientNMB;
26 extern int ClientDGRAM;
27 extern int global_nmb_port;
29 extern int num_response_packets;
31 bool rescan_listen_set = False;
34 /*******************************************************************
35 The global packet linked-list. Incoming entries are
36 added to the end of this list. It is supposed to remain fairly
37 short so we won't bother with an end pointer.
38 ******************************************************************/
40 static struct packet_struct *packet_queue = NULL;
42 /***************************************************************************
43 Utility function to find the specific fd to send a packet out on.
44 **************************************************************************/
46 static int find_subnet_fd_for_address( struct in_addr local_ip )
48 struct subnet_record *subrec;
50 for( subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
51 if(ip_equal_v4(local_ip, subrec->myip))
52 return subrec->nmb_sock;
54 return ClientNMB;
57 /***************************************************************************
58 Utility function to find the specific fd to send a mailslot packet out on.
59 **************************************************************************/
61 static int find_subnet_mailslot_fd_for_address( struct in_addr local_ip )
63 struct subnet_record *subrec;
65 for( subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
66 if(ip_equal_v4(local_ip, subrec->myip))
67 return subrec->dgram_sock;
69 return ClientDGRAM;
72 /***************************************************************************
73 Get/Set problematic nb_flags as network byte order 16 bit int.
74 **************************************************************************/
76 uint16 get_nb_flags(char *buf)
78 return ((((uint16)*buf)&0xFFFF) & NB_FLGMSK);
81 void set_nb_flags(char *buf, uint16 nb_flags)
83 *buf++ = ((nb_flags & NB_FLGMSK) & 0xFF);
84 *buf = '\0';
87 /***************************************************************************
88 Dumps out the browse packet data.
89 **************************************************************************/
91 static void debug_browse_data(char *outbuf, int len)
93 int i,j;
95 DEBUG( 4, ( "debug_browse_data():\n" ) );
96 for (i = 0; i < len; i+= 16) {
97 DEBUGADD( 4, ( "%3x char ", i ) );
99 for (j = 0; j < 16; j++) {
100 unsigned char x;
101 if (i+j >= len)
102 break;
104 x = outbuf[i+j];
105 if (x < 32 || x > 127)
106 x = '.';
108 DEBUGADD( 4, ( "%c", x ) );
111 DEBUGADD( 4, ( "%*s hex", 16-j, "" ) );
113 for (j = 0; j < 16; j++) {
114 if (i+j >= len)
115 break;
116 DEBUGADD( 4, ( " %02x", (unsigned char)outbuf[i+j] ) );
119 DEBUGADD( 4, ("\n") );
123 /***************************************************************************
124 Generates the unique transaction identifier
125 **************************************************************************/
127 static uint16 name_trn_id=0;
129 static uint16 generate_name_trn_id(void)
131 if (!name_trn_id) {
132 name_trn_id = ((unsigned)time(NULL)%(unsigned)0x7FFF) + ((unsigned)sys_getpid()%(unsigned)100);
134 name_trn_id = (name_trn_id+1) % (unsigned)0x7FFF;
135 return name_trn_id;
138 /***************************************************************************
139 Either loops back or sends out a completed NetBIOS packet.
140 **************************************************************************/
142 static bool send_netbios_packet(struct packet_struct *p)
144 bool loopback_this_packet = False;
146 /* Check if we are sending to or from ourselves as a WINS server. */
147 if(ismyip_v4(p->ip) && (p->port == global_nmb_port))
148 loopback_this_packet = True;
150 if(loopback_this_packet) {
151 struct packet_struct *lo_packet = NULL;
152 DEBUG(5,("send_netbios_packet: sending packet to ourselves.\n"));
153 if((lo_packet = copy_packet(p)) == NULL)
154 return False;
155 queue_packet(lo_packet);
156 } else if (!send_packet(p)) {
157 DEBUG(0,("send_netbios_packet: send_packet() to IP %s port %d failed\n",
158 inet_ntoa(p->ip),p->port));
159 return False;
162 return True;
165 /***************************************************************************
166 Sets up the common elements of an outgoing NetBIOS packet.
168 Note: do not attempt to rationalise whether rec_des should be set or not
169 in a particular situation. Just follow rfc_1002 or look at examples from WinXX.
170 It does NOT follow the rule that requests to the wins server always have
171 rec_des true. See for example name releases and refreshes
172 **************************************************************************/
174 static struct packet_struct *create_and_init_netbios_packet(struct nmb_name *nmbname,
175 bool bcast, bool rec_des,
176 struct in_addr to_ip)
178 struct packet_struct *packet = NULL;
179 struct nmb_packet *nmb = NULL;
181 /* Allocate the packet_struct we will return. */
182 if((packet = SMB_MALLOC_P(struct packet_struct)) == NULL) {
183 DEBUG(0,("create_and_init_netbios_packet: malloc fail (1) for packet struct.\n"));
184 return NULL;
187 memset((char *)packet,'\0',sizeof(*packet));
189 nmb = &packet->packet.nmb;
191 nmb->header.name_trn_id = generate_name_trn_id();
192 nmb->header.response = False;
193 nmb->header.nm_flags.recursion_desired = rec_des;
194 nmb->header.nm_flags.recursion_available = False;
195 nmb->header.nm_flags.trunc = False;
196 nmb->header.nm_flags.authoritative = False;
197 nmb->header.nm_flags.bcast = bcast;
199 nmb->header.rcode = 0;
200 nmb->header.qdcount = 1;
201 nmb->header.ancount = 0;
202 nmb->header.nscount = 0;
204 nmb->question.question_name = *nmbname;
205 nmb->question.question_type = QUESTION_TYPE_NB_QUERY;
206 nmb->question.question_class = QUESTION_CLASS_IN;
208 packet->ip = to_ip;
209 packet->port = NMB_PORT;
210 packet->fd = ClientNMB;
211 packet->timestamp = time(NULL);
212 packet->packet_type = NMB_PACKET;
213 packet->locked = False;
215 return packet; /* Caller must free. */
218 /***************************************************************************
219 Sets up the common elements of register, refresh or release packet.
220 **************************************************************************/
222 static bool create_and_init_additional_record(struct packet_struct *packet,
223 uint16 nb_flags,
224 const struct in_addr *register_ip)
226 struct nmb_packet *nmb = &packet->packet.nmb;
228 if((nmb->additional = SMB_MALLOC_P(struct res_rec)) == NULL) {
229 DEBUG(0,("create_and_init_additional_record: malloc fail for additional record.\n"));
230 return False;
233 memset((char *)nmb->additional,'\0',sizeof(struct res_rec));
235 nmb->additional->rr_name = nmb->question.question_name;
236 nmb->additional->rr_type = RR_TYPE_NB;
237 nmb->additional->rr_class = RR_CLASS_IN;
239 /* See RFC 1002, sections 5.1.1.1, 5.1.1.2 and 5.1.1.3 */
240 if (nmb->header.nm_flags.bcast)
241 nmb->additional->ttl = PERMANENT_TTL;
242 else
243 nmb->additional->ttl = lp_max_ttl();
245 nmb->additional->rdlength = 6;
247 set_nb_flags(nmb->additional->rdata,nb_flags);
249 /* Set the address for the name we are registering. */
250 putip(&nmb->additional->rdata[2], register_ip);
253 it turns out that Jeremys code was correct, we are supposed
254 to send registrations from the IP we are registering. The
255 trick is what to do on timeouts! When we send on a
256 non-routable IP then the reply will timeout, and we should
257 treat this as success, not failure. That means we go into
258 our standard refresh cycle for that name which copes nicely
259 with disconnected networks.
261 packet->fd = find_subnet_fd_for_address(*register_ip);
263 return True;
266 /***************************************************************************
267 Sends out a name query.
268 **************************************************************************/
270 static bool initiate_name_query_packet( struct packet_struct *packet)
272 struct nmb_packet *nmb = NULL;
274 nmb = &packet->packet.nmb;
276 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
277 nmb->header.arcount = 0;
279 nmb->header.nm_flags.recursion_desired = True;
281 DEBUG(4,("initiate_name_query_packet: sending query for name %s (bcast=%s) to IP %s\n",
282 nmb_namestr(&nmb->question.question_name),
283 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
285 return send_netbios_packet( packet );
288 /***************************************************************************
289 Sends out a name query - from a WINS server.
290 **************************************************************************/
292 static bool initiate_name_query_packet_from_wins_server( 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 = False;
303 DEBUG(4,("initiate_name_query_packet_from_wins_server: 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 register.
312 **************************************************************************/
314 static bool initiate_name_register_packet( struct packet_struct *packet,
315 uint16 nb_flags, const struct in_addr *register_ip)
317 struct nmb_packet *nmb = &packet->packet.nmb;
319 nmb->header.opcode = NMB_NAME_REG_OPCODE;
320 nmb->header.arcount = 1;
322 nmb->header.nm_flags.recursion_desired = True;
324 if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
325 return False;
327 DEBUG(4,("initiate_name_register_packet: sending registration for name %s (bcast=%s) to IP %s\n",
328 nmb_namestr(&nmb->additional->rr_name),
329 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
331 return send_netbios_packet( packet );
334 /***************************************************************************
335 Sends out a multihomed name register.
336 **************************************************************************/
338 static bool initiate_multihomed_name_register_packet(struct packet_struct *packet,
339 uint16 nb_flags, struct in_addr *register_ip)
341 struct nmb_packet *nmb = &packet->packet.nmb;
342 fstring second_ip_buf;
344 fstrcpy(second_ip_buf, inet_ntoa(packet->ip));
346 nmb->header.opcode = NMB_NAME_MULTIHOMED_REG_OPCODE;
347 nmb->header.arcount = 1;
349 nmb->header.nm_flags.recursion_desired = True;
351 if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
352 return False;
354 DEBUG(4,("initiate_multihomed_name_register_packet: sending registration \
355 for name %s IP %s (bcast=%s) to IP %s\n",
356 nmb_namestr(&nmb->additional->rr_name), inet_ntoa(*register_ip),
357 BOOLSTR(nmb->header.nm_flags.bcast), second_ip_buf ));
359 return send_netbios_packet( packet );
362 /***************************************************************************
363 Sends out a name refresh.
364 **************************************************************************/
366 static bool initiate_name_refresh_packet( struct packet_struct *packet,
367 uint16 nb_flags, struct in_addr *refresh_ip)
369 struct nmb_packet *nmb = &packet->packet.nmb;
371 nmb->header.opcode = NMB_NAME_REFRESH_OPCODE_8;
372 nmb->header.arcount = 1;
374 nmb->header.nm_flags.recursion_desired = False;
376 if(create_and_init_additional_record(packet, nb_flags, refresh_ip) == False)
377 return False;
379 DEBUG(4,("initiate_name_refresh_packet: sending refresh for name %s (bcast=%s) to IP %s\n",
380 nmb_namestr(&nmb->additional->rr_name),
381 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
383 return send_netbios_packet( packet );
386 /***************************************************************************
387 Sends out a name release.
388 **************************************************************************/
390 static bool initiate_name_release_packet( struct packet_struct *packet,
391 uint16 nb_flags, struct in_addr *release_ip)
393 struct nmb_packet *nmb = &packet->packet.nmb;
395 nmb->header.opcode = NMB_NAME_RELEASE_OPCODE;
396 nmb->header.arcount = 1;
398 nmb->header.nm_flags.recursion_desired = False;
400 if(create_and_init_additional_record(packet, nb_flags, release_ip) == False)
401 return False;
403 DEBUG(4,("initiate_name_release_packet: sending release for name %s (bcast=%s) to IP %s\n",
404 nmb_namestr(&nmb->additional->rr_name),
405 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
407 return send_netbios_packet( packet );
410 /***************************************************************************
411 Sends out a node status.
412 **************************************************************************/
414 static bool initiate_node_status_packet( struct packet_struct *packet )
416 struct nmb_packet *nmb = &packet->packet.nmb;
418 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
419 nmb->header.arcount = 0;
421 nmb->header.nm_flags.recursion_desired = False;
423 nmb->question.question_type = QUESTION_TYPE_NB_STATUS;
425 DEBUG(4,("initiate_node_status_packet: sending node status request for name %s to IP %s\n",
426 nmb_namestr(&nmb->question.question_name),
427 inet_ntoa(packet->ip)));
429 return send_netbios_packet( packet );
432 /****************************************************************************
433 Simplification functions for queuing standard packets.
434 These should be the only publicly callable functions for sending
435 out packets.
436 ****************************************************************************/
438 /****************************************************************************
439 Assertion - we should never be sending nmbd packets on the remote
440 broadcast subnet.
441 ****************************************************************************/
443 static bool assert_check_subnet(struct subnet_record *subrec)
445 if( subrec == remote_broadcast_subnet) {
446 DEBUG(0,("assert_check_subnet: Attempt to send packet on remote broadcast subnet. \
447 This is a bug.\n"));
448 return True;
450 return False;
453 /****************************************************************************
454 Queue a register name packet to the broadcast address of a subnet.
455 ****************************************************************************/
457 struct response_record *queue_register_name( struct subnet_record *subrec,
458 response_function resp_fn,
459 timeout_response_function timeout_fn,
460 register_name_success_function success_fn,
461 register_name_fail_function fail_fn,
462 struct userdata_struct *userdata,
463 struct nmb_name *nmbname,
464 uint16 nb_flags)
466 struct packet_struct *p;
467 struct response_record *rrec;
468 struct sockaddr_storage ss;
469 const struct sockaddr_storage *pss = NULL;
470 if(assert_check_subnet(subrec))
471 return NULL;
473 /* note that all name registration requests have RD set (rfc1002 - section 4.2.2 */
474 if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), True,
475 subrec->bcast_ip)) == NULL)
476 return NULL;
478 in_addr_to_sockaddr_storage(&ss, subrec->bcast_ip);
479 pss = iface_ip((struct sockaddr *)&ss);
480 if (!pss || pss->ss_family != AF_INET) {
481 p->locked = False;
482 free_packet(p);
483 return NULL;
486 if(initiate_name_register_packet(p, nb_flags,
487 &((const struct sockaddr_in *)pss)->sin_addr) == False) {
488 p->locked = False;
489 free_packet(p);
490 return NULL;
493 if((rrec = make_response_record(subrec, /* subnet record. */
494 p, /* packet we sent. */
495 resp_fn, /* function to call on response. */
496 timeout_fn, /* function to call on timeout. */
497 (success_function)success_fn, /* function to call on operation success. */
498 (fail_function)fail_fn, /* function to call on operation fail. */
499 userdata)) == NULL) {
500 p->locked = False;
501 free_packet(p);
502 return NULL;
505 return rrec;
508 /****************************************************************************
509 Queue a refresh name packet to the broadcast address of a subnet.
510 ****************************************************************************/
512 void queue_wins_refresh(struct nmb_name *nmbname,
513 response_function resp_fn,
514 timeout_response_function timeout_fn,
515 uint16 nb_flags,
516 struct in_addr refresh_ip,
517 const char *tag)
519 struct packet_struct *p;
520 struct response_record *rrec;
521 struct in_addr wins_ip;
522 struct userdata_struct *userdata;
523 fstring ip_str;
525 wins_ip = wins_srv_ip_tag(tag, refresh_ip);
527 if ((p = create_and_init_netbios_packet(nmbname, False, False, wins_ip)) == NULL) {
528 return;
531 if (!initiate_name_refresh_packet(p, nb_flags, &refresh_ip)) {
532 p->locked = False;
533 free_packet(p);
534 return;
537 fstrcpy(ip_str, inet_ntoa(refresh_ip));
539 DEBUG(6,("Refreshing name %s IP %s with WINS server %s using tag '%s'\n",
540 nmb_namestr(nmbname), ip_str, inet_ntoa(wins_ip), tag));
542 userdata = (struct userdata_struct *)SMB_MALLOC(sizeof(*userdata) + strlen(tag) + 1);
543 if (!userdata) {
544 p->locked = False;
545 free_packet(p);
546 DEBUG(0,("Failed to allocate userdata structure!\n"));
547 return;
549 ZERO_STRUCTP(userdata);
550 userdata->userdata_len = strlen(tag) + 1;
551 strlcpy(userdata->data, tag, userdata->userdata_len);
553 if ((rrec = make_response_record(unicast_subnet,
555 resp_fn, timeout_fn,
556 NULL,
557 NULL,
558 userdata)) == NULL) {
559 p->locked = False;
560 free_packet(p);
561 return;
564 free(userdata);
566 /* we don't want to repeat refresh packets */
567 rrec->repeat_count = 0;
571 /****************************************************************************
572 Queue a multihomed register name packet to a given WINS server IP
573 ****************************************************************************/
575 struct response_record *queue_register_multihomed_name( struct subnet_record *subrec,
576 response_function resp_fn,
577 timeout_response_function timeout_fn,
578 register_name_success_function success_fn,
579 register_name_fail_function fail_fn,
580 struct userdata_struct *userdata,
581 struct nmb_name *nmbname,
582 uint16 nb_flags,
583 struct in_addr register_ip,
584 struct in_addr wins_ip)
586 struct packet_struct *p;
587 struct response_record *rrec;
588 bool ret;
590 /* Sanity check. */
591 if(subrec != unicast_subnet) {
592 DEBUG(0,("queue_register_multihomed_name: should only be done on \
593 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
594 return NULL;
597 if(assert_check_subnet(subrec))
598 return NULL;
600 if ((p = create_and_init_netbios_packet(nmbname, False, True, wins_ip)) == NULL)
601 return NULL;
603 if (nb_flags & NB_GROUP)
604 ret = initiate_name_register_packet( p, nb_flags, &register_ip);
605 else
606 ret = initiate_multihomed_name_register_packet(p, nb_flags, &register_ip);
608 if (ret == False) {
609 p->locked = False;
610 free_packet(p);
611 return NULL;
614 if ((rrec = make_response_record(subrec, /* subnet record. */
615 p, /* packet we sent. */
616 resp_fn, /* function to call on response. */
617 timeout_fn, /* function to call on timeout. */
618 (success_function)success_fn, /* function to call on operation success. */
619 (fail_function)fail_fn, /* function to call on operation fail. */
620 userdata)) == NULL) {
621 p->locked = False;
622 free_packet(p);
623 return NULL;
626 return rrec;
629 /****************************************************************************
630 Queue a release name packet to the broadcast address of a subnet.
631 ****************************************************************************/
633 struct response_record *queue_release_name( struct subnet_record *subrec,
634 response_function resp_fn,
635 timeout_response_function timeout_fn,
636 release_name_success_function success_fn,
637 release_name_fail_function fail_fn,
638 struct userdata_struct *userdata,
639 struct nmb_name *nmbname,
640 uint16 nb_flags,
641 struct in_addr release_ip,
642 struct in_addr dest_ip)
644 struct packet_struct *p;
645 struct response_record *rrec;
647 if(assert_check_subnet(subrec))
648 return NULL;
650 if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), False, dest_ip)) == NULL)
651 return NULL;
653 if(initiate_name_release_packet( p, nb_flags, &release_ip) == False) {
654 p->locked = False;
655 free_packet(p);
656 return NULL;
659 if((rrec = make_response_record(subrec, /* subnet record. */
660 p, /* packet we sent. */
661 resp_fn, /* function to call on response. */
662 timeout_fn, /* function to call on timeout. */
663 (success_function)success_fn, /* function to call on operation success. */
664 (fail_function)fail_fn, /* function to call on operation fail. */
665 userdata)) == NULL) {
666 p->locked = False;
667 free_packet(p);
668 return NULL;
672 * For a broadcast release packet, only send once.
673 * This will cause us to remove the name asap. JRA.
676 if (subrec != unicast_subnet) {
677 rrec->repeat_count = 0;
678 rrec->repeat_time = 0;
681 return rrec;
684 /****************************************************************************
685 Queue a query name packet to the broadcast address of a subnet.
686 ****************************************************************************/
688 struct response_record *queue_query_name( struct subnet_record *subrec,
689 response_function resp_fn,
690 timeout_response_function timeout_fn,
691 query_name_success_function success_fn,
692 query_name_fail_function fail_fn,
693 struct userdata_struct *userdata,
694 struct nmb_name *nmbname)
696 struct packet_struct *p;
697 struct response_record *rrec;
698 struct in_addr to_ip;
700 if(assert_check_subnet(subrec))
701 return NULL;
703 to_ip = subrec->bcast_ip;
705 /* queries to the WINS server turn up here as queries to IP 0.0.0.0
706 These need to be handled a bit differently */
707 if (subrec->type == UNICAST_SUBNET && is_zero_ip_v4(to_ip)) {
708 /* What we really need to do is loop over each of our wins
709 * servers and wins server tags here, but that just doesn't
710 * fit our architecture at the moment (userdata may already
711 * be used when we get here). For now we just query the first
712 * active wins server on the first tag.
714 char **tags = wins_srv_tags();
715 if (!tags) {
716 return NULL;
718 to_ip = wins_srv_ip_tag(tags[0], to_ip);
719 wins_srv_tags_free(tags);
722 if(( p = create_and_init_netbios_packet(nmbname,
723 (subrec != unicast_subnet),
724 (subrec == unicast_subnet),
725 to_ip)) == NULL)
726 return NULL;
728 if(lp_bind_interfaces_only()) {
729 int i;
731 DEBUG(10,("queue_query_name: bind_interfaces_only is set, looking for suitable source IP\n"));
732 for(i = 0; i < iface_count(); i++) {
733 const struct in_addr *ifip = iface_n_ip_v4(i);
735 if (ifip == NULL) {
736 DEBUG(0,("queue_query_name: interface %d has NULL IP address !\n", i));
737 continue;
740 if (is_loopback_ip_v4(*ifip)) {
741 DEBUG(5,("queue_query_name: ignoring loopback interface (%d)\n", i));
742 continue;
745 DEBUG(10,("queue_query_name: using source IP %s\n",inet_ntoa(*ifip)));
746 p->fd = find_subnet_fd_for_address( *ifip );
747 break;
751 if(initiate_name_query_packet( p ) == False) {
752 p->locked = False;
753 free_packet(p);
754 return NULL;
757 if((rrec = make_response_record(subrec, /* subnet record. */
758 p, /* packet we sent. */
759 resp_fn, /* function to call on response. */
760 timeout_fn, /* function to call on timeout. */
761 (success_function)success_fn, /* function to call on operation success. */
762 (fail_function)fail_fn, /* function to call on operation fail. */
763 userdata)) == NULL) {
764 p->locked = False;
765 free_packet(p);
766 return NULL;
769 return rrec;
772 /****************************************************************************
773 Queue a query name packet to a given address from the WINS subnet.
774 ****************************************************************************/
776 struct response_record *queue_query_name_from_wins_server( struct in_addr to_ip,
777 response_function resp_fn,
778 timeout_response_function timeout_fn,
779 query_name_success_function success_fn,
780 query_name_fail_function fail_fn,
781 struct userdata_struct *userdata,
782 struct nmb_name *nmbname)
784 struct packet_struct *p;
785 struct response_record *rrec;
787 if ((p = create_and_init_netbios_packet(nmbname, False, False, to_ip)) == NULL)
788 return NULL;
790 if(initiate_name_query_packet_from_wins_server( p ) == False) {
791 p->locked = False;
792 free_packet(p);
793 return NULL;
796 if((rrec = make_response_record(wins_server_subnet, /* subnet record. */
797 p, /* packet we sent. */
798 resp_fn, /* function to call on response. */
799 timeout_fn, /* function to call on timeout. */
800 (success_function)success_fn, /* function to call on operation success. */
801 (fail_function)fail_fn, /* function to call on operation fail. */
802 userdata)) == NULL) {
803 p->locked = False;
804 free_packet(p);
805 return NULL;
808 return rrec;
811 /****************************************************************************
812 Queue a node status packet to a given name and address.
813 ****************************************************************************/
815 struct response_record *queue_node_status( struct subnet_record *subrec,
816 response_function resp_fn,
817 timeout_response_function timeout_fn,
818 node_status_success_function success_fn,
819 node_status_fail_function fail_fn,
820 struct userdata_struct *userdata,
821 struct nmb_name *nmbname,
822 struct in_addr send_ip)
824 struct packet_struct *p;
825 struct response_record *rrec;
827 /* Sanity check. */
828 if(subrec != unicast_subnet) {
829 DEBUG(0,("queue_register_multihomed_name: should only be done on \
830 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
831 return NULL;
834 if(assert_check_subnet(subrec))
835 return NULL;
837 if(( p = create_and_init_netbios_packet(nmbname, False, False, send_ip)) == NULL)
838 return NULL;
840 if(initiate_node_status_packet(p) == False) {
841 p->locked = False;
842 free_packet(p);
843 return NULL;
846 if((rrec = make_response_record(subrec, /* subnet record. */
847 p, /* packet we sent. */
848 resp_fn, /* function to call on response. */
849 timeout_fn, /* function to call on timeout. */
850 (success_function)success_fn, /* function to call on operation success. */
851 (fail_function)fail_fn, /* function to call on operation fail. */
852 userdata)) == NULL) {
853 p->locked = False;
854 free_packet(p);
855 return NULL;
858 return rrec;
861 /****************************************************************************
862 Reply to a netbios name packet. see rfc1002.txt
863 ****************************************************************************/
865 void reply_netbios_packet(struct packet_struct *orig_packet,
866 int rcode, enum netbios_reply_type_code rcv_code, int opcode,
867 int ttl, char *data,int len)
869 struct packet_struct packet;
870 struct nmb_packet *nmb = NULL;
871 struct res_rec answers;
872 struct nmb_packet *orig_nmb = &orig_packet->packet.nmb;
873 bool loopback_this_packet = False;
874 int rr_type = RR_TYPE_NB;
875 const char *packet_type = "unknown";
877 /* Check if we are sending to or from ourselves. */
878 if(ismyip_v4(orig_packet->ip) && (orig_packet->port == global_nmb_port))
879 loopback_this_packet = True;
881 nmb = &packet.packet.nmb;
883 /* Do a partial copy of the packet. We clear the locked flag and
884 the resource record pointers. */
885 packet = *orig_packet; /* Full structure copy. */
886 packet.locked = False;
887 nmb->answers = NULL;
888 nmb->nsrecs = NULL;
889 nmb->additional = NULL;
891 switch (rcv_code) {
892 case NMB_STATUS:
893 packet_type = "nmb_status";
894 nmb->header.nm_flags.recursion_desired = False;
895 nmb->header.nm_flags.recursion_available = False;
896 rr_type = RR_TYPE_NBSTAT;
897 break;
898 case NMB_QUERY:
899 packet_type = "nmb_query";
900 nmb->header.nm_flags.recursion_desired = True;
901 nmb->header.nm_flags.recursion_available = True;
902 if (rcode) {
903 rr_type = RR_TYPE_NULL;
905 break;
906 case NMB_REG:
907 case NMB_REG_REFRESH:
908 packet_type = "nmb_reg";
909 nmb->header.nm_flags.recursion_desired = True;
910 nmb->header.nm_flags.recursion_available = True;
911 break;
912 case NMB_REL:
913 packet_type = "nmb_rel";
914 nmb->header.nm_flags.recursion_desired = False;
915 nmb->header.nm_flags.recursion_available = False;
916 break;
917 case NMB_WAIT_ACK:
918 packet_type = "nmb_wack";
919 nmb->header.nm_flags.recursion_desired = False;
920 nmb->header.nm_flags.recursion_available = False;
921 rr_type = RR_TYPE_NULL;
922 break;
923 case WINS_REG:
924 packet_type = "wins_reg";
925 nmb->header.nm_flags.recursion_desired = True;
926 nmb->header.nm_flags.recursion_available = True;
927 break;
928 case WINS_QUERY:
929 packet_type = "wins_query";
930 nmb->header.nm_flags.recursion_desired = True;
931 nmb->header.nm_flags.recursion_available = True;
932 if (rcode) {
933 rr_type = RR_TYPE_NULL;
935 break;
936 default:
937 DEBUG(0,("reply_netbios_packet: Unknown packet type: %s %s to ip %s\n",
938 packet_type, nmb_namestr(&orig_nmb->question.question_name),
939 inet_ntoa(packet.ip)));
940 return;
943 DEBUG(4,("reply_netbios_packet: sending a reply of packet type: %s %s to ip %s \
944 for id %hu\n", packet_type, nmb_namestr(&orig_nmb->question.question_name),
945 inet_ntoa(packet.ip), orig_nmb->header.name_trn_id));
947 nmb->header.name_trn_id = orig_nmb->header.name_trn_id;
948 nmb->header.opcode = opcode;
949 nmb->header.response = True;
950 nmb->header.nm_flags.bcast = False;
951 nmb->header.nm_flags.trunc = False;
952 nmb->header.nm_flags.authoritative = True;
954 nmb->header.rcode = rcode;
955 nmb->header.qdcount = 0;
956 nmb->header.ancount = 1;
957 nmb->header.nscount = 0;
958 nmb->header.arcount = 0;
960 memset((char*)&nmb->question,'\0',sizeof(nmb->question));
962 nmb->answers = &answers;
963 memset((char*)nmb->answers,'\0',sizeof(*nmb->answers));
965 nmb->answers->rr_name = orig_nmb->question.question_name;
966 nmb->answers->rr_type = rr_type;
967 nmb->answers->rr_class = RR_CLASS_IN;
968 nmb->answers->ttl = ttl;
970 if (data && len) {
971 if (len < 0 || len > sizeof(nmb->answers->rdata)) {
972 DEBUG(5,("reply_netbios_packet: "
973 "invalid packet len (%d)\n",
974 len ));
975 return;
977 nmb->answers->rdlength = len;
978 memcpy(nmb->answers->rdata, data, len);
981 packet.packet_type = NMB_PACKET;
982 /* Ensure we send out on the same fd that the original
983 packet came in on to give the correct source IP address. */
984 packet.fd = orig_packet->fd;
985 packet.timestamp = time(NULL);
987 debug_nmb_packet(&packet);
989 if(loopback_this_packet) {
990 struct packet_struct *lo_packet;
991 DEBUG(5,("reply_netbios_packet: sending packet to ourselves.\n"));
992 if((lo_packet = copy_packet(&packet)) == NULL)
993 return;
994 queue_packet(lo_packet);
995 } else if (!send_packet(&packet)) {
996 DEBUG(0,("reply_netbios_packet: send_packet to IP %s port %d failed\n",
997 inet_ntoa(packet.ip),packet.port));
1001 /*******************************************************************
1002 Queue a packet into a packet queue
1003 ******************************************************************/
1005 void queue_packet(struct packet_struct *packet)
1007 struct packet_struct *p;
1009 if (!packet_queue) {
1010 packet->prev = NULL;
1011 packet->next = NULL;
1012 packet_queue = packet;
1013 return;
1016 /* find the bottom */
1017 for (p=packet_queue;p->next;p=p->next)
1020 p->next = packet;
1021 packet->next = NULL;
1022 packet->prev = p;
1025 /****************************************************************************
1026 Try and find a matching subnet record for a datagram port 138 packet.
1027 ****************************************************************************/
1029 static struct subnet_record *find_subnet_for_dgram_browse_packet(struct packet_struct *p)
1031 struct subnet_record *subrec;
1033 /* Go through all the broadcast subnets and see if the mask matches. */
1034 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1035 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1036 return subrec;
1039 /* If the subnet record is the remote announce broadcast subnet,
1040 hack it here to be the first subnet. This is really gross and
1041 is needed due to people turning on port 137/138 broadcast
1042 forwarding on their routers. May fire and brimstone rain
1043 down upon them...
1046 return FIRST_SUBNET;
1049 /****************************************************************************
1050 Dispatch a browse frame from port 138 to the correct processing function.
1051 ****************************************************************************/
1053 static void process_browse_packet(struct packet_struct *p, char *buf,int len)
1055 struct dgram_packet *dgram = &p->packet.dgram;
1056 int command = CVAL(buf,0);
1057 struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1058 char scope[64];
1059 unstring src_name;
1061 /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1062 pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1063 if (!strequal(scope, global_scope())) {
1064 DEBUG(7,("process_browse_packet: Discarding datagram from IP %s. Scope (%s) \
1065 mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
1066 return;
1069 pull_ascii_nstring(src_name, sizeof(src_name), dgram->source_name.name);
1070 if (is_myname(src_name)) {
1071 DEBUG(0,("process_browse_packet: Discarding datagram from IP %s. Source name \
1072 %s is one of our names !\n", inet_ntoa(p->ip), nmb_namestr(&dgram->source_name)));
1073 return;
1076 switch (command) {
1077 case ANN_HostAnnouncement:
1078 debug_browse_data(buf, len);
1079 process_host_announce(subrec, p, buf+1);
1080 break;
1081 case ANN_DomainAnnouncement:
1082 debug_browse_data(buf, len);
1083 process_workgroup_announce(subrec, p, buf+1);
1084 break;
1085 case ANN_LocalMasterAnnouncement:
1086 debug_browse_data(buf, len);
1087 process_local_master_announce(subrec, p, buf+1);
1088 break;
1089 case ANN_AnnouncementRequest:
1090 debug_browse_data(buf, len);
1091 process_announce_request(subrec, p, buf+1);
1092 break;
1093 case ANN_Election:
1094 debug_browse_data(buf, len);
1095 process_election(subrec, p, buf+1);
1096 break;
1097 case ANN_GetBackupListReq:
1098 debug_browse_data(buf, len);
1099 process_get_backup_list_request(subrec, p, buf+1);
1100 break;
1101 case ANN_GetBackupListResp:
1102 debug_browse_data(buf, len);
1103 /* We never send ANN_GetBackupListReq so we should never get these. */
1104 DEBUG(0,("process_browse_packet: Discarding GetBackupListResponse \
1105 packet from %s IP %s\n", nmb_namestr(&dgram->source_name), inet_ntoa(p->ip)));
1106 break;
1107 case ANN_ResetBrowserState:
1108 debug_browse_data(buf, len);
1109 process_reset_browser(subrec, p, buf+1);
1110 break;
1111 case ANN_MasterAnnouncement:
1112 /* Master browser datagrams must be processed on the unicast subnet. */
1113 subrec = unicast_subnet;
1115 debug_browse_data(buf, len);
1116 process_master_browser_announce(subrec, p, buf+1);
1117 break;
1118 case ANN_BecomeBackup:
1120 * We don't currently implement this. Log it just in case.
1122 debug_browse_data(buf, len);
1123 DEBUG(10,("process_browse_packet: On subnet %s ignoring browse packet \
1124 command ANN_BecomeBackup from %s IP %s to %s\n", subrec->subnet_name, nmb_namestr(&dgram->source_name),
1125 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1126 break;
1127 default:
1128 debug_browse_data(buf, len);
1129 DEBUG(0,("process_browse_packet: On subnet %s ignoring browse packet \
1130 command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namestr(&dgram->source_name),
1131 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1132 break;
1136 /****************************************************************************
1137 Dispatch a LanMan browse frame from port 138 to the correct processing function.
1138 ****************************************************************************/
1140 static void process_lanman_packet(struct packet_struct *p, char *buf,int len)
1142 struct dgram_packet *dgram = &p->packet.dgram;
1143 int command = SVAL(buf,0);
1144 struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1145 char scope[64];
1146 unstring src_name;
1148 /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1150 pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1151 if (!strequal(scope, global_scope())) {
1152 DEBUG(7,("process_lanman_packet: Discarding datagram from IP %s. Scope (%s) \
1153 mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
1154 return;
1157 pull_ascii_nstring(src_name, sizeof(src_name), dgram->source_name.name);
1158 if (is_myname(src_name)) {
1159 DEBUG(0,("process_lanman_packet: Discarding datagram from IP %s. Source name \
1160 %s is one of our names !\n", inet_ntoa(p->ip), nmb_namestr(&dgram->source_name)));
1161 return;
1164 switch (command) {
1165 case ANN_HostAnnouncement:
1166 debug_browse_data(buf, len);
1167 process_lm_host_announce(subrec, p, buf+1, len > 1 ? len-1 : 0);
1168 break;
1169 case ANN_AnnouncementRequest:
1170 process_lm_announce_request(subrec, p, buf+1, len > 1 ? len-1 : 0);
1171 break;
1172 default:
1173 DEBUG(0,("process_lanman_packet: On subnet %s ignoring browse packet \
1174 command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namestr(&dgram->source_name),
1175 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1176 break;
1180 /****************************************************************************
1181 Determine if a packet is for us on port 138. Note that to have any chance of
1182 being efficient we need to drop as many packets as possible at this
1183 stage as subsequent processing is expensive.
1184 ****************************************************************************/
1186 static bool listening(struct packet_struct *p,struct nmb_name *nbname)
1188 struct subnet_record *subrec = NULL;
1190 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1191 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1192 break;
1195 if(subrec == NULL)
1196 subrec = unicast_subnet;
1198 return (find_name_on_subnet(subrec, nbname, FIND_SELF_NAME) != NULL);
1201 /****************************************************************************
1202 Process udp 138 datagrams
1203 ****************************************************************************/
1205 static void process_dgram(struct packet_struct *p)
1207 char *buf;
1208 char *buf2;
1209 int len;
1210 struct dgram_packet *dgram = &p->packet.dgram;
1212 /* If we aren't listening to the destination name then ignore the packet */
1213 if (!listening(p,&dgram->dest_name)) {
1214 unexpected_packet(p);
1215 DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from %s\n",
1216 nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip)));
1217 return;
1220 if (dgram->header.msg_type != 0x10 && dgram->header.msg_type != 0x11 && dgram->header.msg_type != 0x12) {
1221 unexpected_packet(p);
1222 /* Don't process error packets etc yet */
1223 DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from IP %s as it is \
1224 an error packet of type %x\n", nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip), dgram->header.msg_type));
1225 return;
1228 /* Ensure we have a large enough packet before looking inside. */
1229 if (dgram->datasize < (smb_vwv12 - 2)) {
1230 /* That's the offset minus the 4 byte length + 2 bytes of offset. */
1231 DEBUG(0,("process_dgram: ignoring too short dgram packet (%u) sent to name %s from IP %s\n",
1232 (unsigned int)dgram->datasize,
1233 nmb_namestr(&dgram->dest_name),
1234 inet_ntoa(p->ip) ));
1235 return;
1238 buf = &dgram->data[0];
1239 buf -= 4; /* XXXX for the pseudo tcp length - someday I need to get rid of this */
1241 if (CVAL(buf,smb_com) != SMBtrans)
1242 return;
1244 len = SVAL(buf,smb_vwv11);
1245 buf2 = smb_base(buf) + SVAL(buf,smb_vwv12);
1247 if (len <= 0 || len > dgram->datasize) {
1248 DEBUG(0,("process_dgram: ignoring malformed1 (datasize = %d, len = %d) datagram \
1249 packet sent to name %s from IP %s\n",
1250 dgram->datasize,
1251 len,
1252 nmb_namestr(&dgram->dest_name),
1253 inet_ntoa(p->ip) ));
1254 return;
1257 if (buf2 < dgram->data || (buf2 >= dgram->data + dgram->datasize)) {
1258 DEBUG(0,("process_dgram: ignoring malformed2 (datasize = %d, len=%d, off=%d) datagram \
1259 packet sent to name %s from IP %s\n",
1260 dgram->datasize,
1261 len,
1262 (int)PTR_DIFF(buf2, dgram->data),
1263 nmb_namestr(&dgram->dest_name),
1264 inet_ntoa(p->ip) ));
1265 return;
1268 if ((buf2 + len < dgram->data) || (buf2 + len > dgram->data + dgram->datasize)) {
1269 DEBUG(0,("process_dgram: ignoring malformed3 (datasize = %d, len=%d, off=%d) datagram \
1270 packet sent to name %s from IP %s\n",
1271 dgram->datasize,
1272 len,
1273 (int)PTR_DIFF(buf2, dgram->data),
1274 nmb_namestr(&dgram->dest_name),
1275 inet_ntoa(p->ip) ));
1276 return;
1279 DEBUG(4,("process_dgram: datagram from %s to %s IP %s for %s of type %d len=%d\n",
1280 nmb_namestr(&dgram->source_name),nmb_namestr(&dgram->dest_name),
1281 inet_ntoa(p->ip), smb_buf(buf),CVAL(buf2,0),len));
1283 /* Datagram packet received for the browser mailslot */
1284 if (strequal(smb_buf(buf),BROWSE_MAILSLOT)) {
1285 process_browse_packet(p,buf2,len);
1286 return;
1289 /* Datagram packet received for the LAN Manager mailslot */
1290 if (strequal(smb_buf(buf),LANMAN_MAILSLOT)) {
1291 process_lanman_packet(p,buf2,len);
1292 return;
1295 /* Datagram packet received for the domain logon mailslot */
1296 if (strequal(smb_buf(buf),NET_LOGON_MAILSLOT)) {
1297 process_logon_packet(p,buf2,len,NET_LOGON_MAILSLOT);
1298 return;
1301 /* Datagram packet received for the NT domain logon mailslot */
1302 if (strequal(smb_buf(buf),NT_LOGON_MAILSLOT)) {
1303 process_logon_packet(p,buf2,len,NT_LOGON_MAILSLOT);
1304 return;
1307 unexpected_packet(p);
1310 /****************************************************************************
1311 Validate a response nmb packet.
1312 ****************************************************************************/
1314 static bool validate_nmb_response_packet( struct nmb_packet *nmb )
1316 bool ignore = False;
1318 switch (nmb->header.opcode) {
1319 case NMB_NAME_REG_OPCODE:
1320 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1321 case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1322 if (nmb->header.ancount == 0) {
1323 DEBUG(0,("validate_nmb_response_packet: Bad REG/REFRESH Packet. "));
1324 ignore = True;
1326 break;
1328 case NMB_NAME_QUERY_OPCODE:
1329 if ((nmb->header.ancount != 0) && (nmb->header.ancount != 1)) {
1330 DEBUG(0,("validate_nmb_response_packet: Bad QUERY Packet. "));
1331 ignore = True;
1333 break;
1335 case NMB_NAME_RELEASE_OPCODE:
1336 if (nmb->header.ancount == 0) {
1337 DEBUG(0,("validate_nmb_response_packet: Bad RELEASE Packet. "));
1338 ignore = True;
1340 break;
1342 case NMB_WACK_OPCODE:
1343 /* Check WACK response here. */
1344 if (nmb->header.ancount != 1) {
1345 DEBUG(0,("validate_nmb_response_packet: Bad WACK Packet. "));
1346 ignore = True;
1348 break;
1349 default:
1350 DEBUG(0,("validate_nmb_response_packet: Ignoring packet with unknown opcode %d.\n",
1351 nmb->header.opcode));
1352 return True;
1355 if(ignore)
1356 DEBUG(0,("Ignoring response packet with opcode %d.\n", nmb->header.opcode));
1358 return ignore;
1361 /****************************************************************************
1362 Validate a request nmb packet.
1363 ****************************************************************************/
1365 static bool validate_nmb_packet( struct nmb_packet *nmb )
1367 bool ignore = False;
1369 switch (nmb->header.opcode) {
1370 case NMB_NAME_REG_OPCODE:
1371 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1372 case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1373 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1374 if (nmb->header.qdcount==0 || nmb->header.arcount==0) {
1375 DEBUG(0,("validate_nmb_packet: Bad REG/REFRESH Packet. "));
1376 ignore = True;
1378 break;
1380 case NMB_NAME_QUERY_OPCODE:
1381 if ((nmb->header.qdcount == 0) || ((nmb->question.question_type != QUESTION_TYPE_NB_QUERY) &&
1382 (nmb->question.question_type != QUESTION_TYPE_NB_STATUS))) {
1383 DEBUG(0,("validate_nmb_packet: Bad QUERY Packet. "));
1384 ignore = True;
1386 break;
1388 case NMB_NAME_RELEASE_OPCODE:
1389 if (nmb->header.qdcount==0 || nmb->header.arcount==0) {
1390 DEBUG(0,("validate_nmb_packet: Bad RELEASE Packet. "));
1391 ignore = True;
1393 break;
1394 default:
1395 DEBUG(0,("validate_nmb_packet: Ignoring packet with unknown opcode %d.\n",
1396 nmb->header.opcode));
1397 return True;
1400 if(ignore)
1401 DEBUG(0,("validate_nmb_packet: Ignoring request packet with opcode %d.\n", nmb->header.opcode));
1403 return ignore;
1406 /****************************************************************************
1407 Find a subnet (and potentially a response record) for a packet.
1408 ****************************************************************************/
1410 static struct subnet_record *find_subnet_for_nmb_packet( struct packet_struct *p,
1411 struct response_record **pprrec)
1413 struct nmb_packet *nmb = &p->packet.nmb;
1414 struct response_record *rrec = NULL;
1415 struct subnet_record *subrec = NULL;
1417 if(pprrec != NULL)
1418 *pprrec = NULL;
1420 if(nmb->header.response) {
1421 /* It's a response packet. Find a record for it or it's an error. */
1423 rrec = find_response_record( &subrec, nmb->header.name_trn_id);
1424 if(rrec == NULL) {
1425 DEBUG(3,("find_subnet_for_nmb_packet: response record not found for response id %hu\n",
1426 nmb->header.name_trn_id));
1427 unexpected_packet(p);
1428 return NULL;
1431 if(subrec == NULL) {
1432 DEBUG(0,("find_subnet_for_nmb_packet: subnet record not found for response id %hu\n",
1433 nmb->header.name_trn_id));
1434 return NULL;
1437 if(pprrec != NULL)
1438 *pprrec = rrec;
1439 return subrec;
1442 /* Try and see what subnet this packet belongs to. */
1444 /* WINS server ? */
1445 if(packet_is_for_wins_server(p))
1446 return wins_server_subnet;
1448 /* If it wasn't a broadcast packet then send to the UNICAST subnet. */
1449 if(nmb->header.nm_flags.bcast == False)
1450 return unicast_subnet;
1452 /* Go through all the broadcast subnets and see if the mask matches. */
1453 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1454 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1455 return subrec;
1458 /* If none match it must have been a directed broadcast - assign the remote_broadcast_subnet. */
1459 return remote_broadcast_subnet;
1462 /****************************************************************************
1463 Process a nmb request packet - validate the packet and route it.
1464 ****************************************************************************/
1466 static void process_nmb_request(struct packet_struct *p)
1468 struct nmb_packet *nmb = &p->packet.nmb;
1469 struct subnet_record *subrec = NULL;
1471 debug_nmb_packet(p);
1473 /* Ensure we have a good packet. */
1474 if(validate_nmb_packet(nmb))
1475 return;
1477 /* Allocate a subnet to this packet - if we cannot - fail. */
1478 if((subrec = find_subnet_for_nmb_packet(p, NULL))==NULL)
1479 return;
1481 switch (nmb->header.opcode) {
1482 case NMB_NAME_REG_OPCODE:
1483 if(subrec == wins_server_subnet)
1484 wins_process_name_registration_request(subrec, p);
1485 else
1486 process_name_registration_request(subrec, p);
1487 break;
1489 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1490 case NMB_NAME_REFRESH_OPCODE_9:
1491 if(subrec == wins_server_subnet)
1492 wins_process_name_refresh_request(subrec, p);
1493 else
1494 process_name_refresh_request(subrec, p);
1495 break;
1497 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1498 if(subrec == wins_server_subnet) {
1499 wins_process_multihomed_name_registration_request(subrec, p);
1500 } else {
1501 DEBUG(0,("process_nmb_request: Multihomed registration request must be \
1502 directed at a WINS server.\n"));
1504 break;
1506 case NMB_NAME_QUERY_OPCODE:
1507 switch (nmb->question.question_type) {
1508 case QUESTION_TYPE_NB_QUERY:
1509 if(subrec == wins_server_subnet)
1510 wins_process_name_query_request(subrec, p);
1511 else
1512 process_name_query_request(subrec, p);
1513 break;
1514 case QUESTION_TYPE_NB_STATUS:
1515 if(subrec == wins_server_subnet) {
1516 DEBUG(0,("process_nmb_request: NB_STATUS request directed at WINS server is \
1517 not allowed.\n"));
1518 break;
1519 } else {
1520 process_node_status_request(subrec, p);
1522 break;
1524 break;
1526 case NMB_NAME_RELEASE_OPCODE:
1527 if(subrec == wins_server_subnet)
1528 wins_process_name_release_request(subrec, p);
1529 else
1530 process_name_release_request(subrec, p);
1531 break;
1535 /****************************************************************************
1536 Process a nmb response packet - validate the packet and route it.
1537 to either the WINS server or a normal response.
1538 ****************************************************************************/
1540 static void process_nmb_response(struct packet_struct *p)
1542 struct nmb_packet *nmb = &p->packet.nmb;
1543 struct subnet_record *subrec = NULL;
1544 struct response_record *rrec = NULL;
1546 debug_nmb_packet(p);
1548 if(validate_nmb_response_packet(nmb))
1549 return;
1551 if((subrec = find_subnet_for_nmb_packet(p, &rrec))==NULL)
1552 return;
1554 if(rrec == NULL) {
1555 DEBUG(0,("process_nmb_response: response packet received but no response record \
1556 found for id = %hu. Ignoring packet.\n", nmb->header.name_trn_id));
1557 return;
1560 /* Increment the number of responses received for this record. */
1561 rrec->num_msgs++;
1562 /* Ensure we don't re-send the request. */
1563 rrec->repeat_count = 0;
1565 /* Call the response received function for this packet. */
1566 (*rrec->resp_fn)(subrec, rrec, p);
1569 /*******************************************************************
1570 Run elements off the packet queue till its empty
1571 ******************************************************************/
1573 void run_packet_queue(void)
1575 struct packet_struct *p;
1577 while ((p = packet_queue)) {
1578 packet_queue = p->next;
1579 if (packet_queue)
1580 packet_queue->prev = NULL;
1581 p->next = p->prev = NULL;
1583 switch (p->packet_type) {
1584 case NMB_PACKET:
1585 if(p->packet.nmb.header.response)
1586 process_nmb_response(p);
1587 else
1588 process_nmb_request(p);
1589 break;
1591 case DGRAM_PACKET:
1592 process_dgram(p);
1593 break;
1595 free_packet(p);
1599 /*******************************************************************
1600 Retransmit or timeout elements from all the outgoing subnet response
1601 record queues. NOTE that this code must also check the WINS server
1602 subnet for response records to timeout as the WINS server code
1603 can send requests to check if a client still owns a name.
1604 (Patch from Andrey Alekseyev <fetch@muffin.arcadia.spb.ru>).
1605 ******************************************************************/
1607 void retransmit_or_expire_response_records(time_t t)
1609 struct subnet_record *subrec;
1611 for (subrec = FIRST_SUBNET; subrec; subrec = get_next_subnet_maybe_unicast_or_wins_server(subrec)) {
1612 struct response_record *rrec, *nextrrec;
1614 restart:
1616 for (rrec = subrec->responselist; rrec; rrec = nextrrec) {
1617 nextrrec = rrec->next;
1619 if (rrec->repeat_time <= t) {
1620 if (rrec->repeat_count > 0) {
1621 /* Resend while we have a non-zero repeat_count. */
1622 if(!send_packet(rrec->packet)) {
1623 DEBUG(0,("retransmit_or_expire_response_records: Failed to resend packet id %hu \
1624 to IP %s on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1626 rrec->repeat_time = t + rrec->repeat_interval;
1627 rrec->repeat_count--;
1628 } else {
1629 DEBUG(4,("retransmit_or_expire_response_records: timeout for packet id %hu to IP %s \
1630 on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1633 * Check the flag in this record to prevent recursion if we end
1634 * up in this function again via the timeout function call.
1637 if(!rrec->in_expiration_processing) {
1640 * Set the recursion protection flag in this record.
1643 rrec->in_expiration_processing = True;
1645 /* Call the timeout function. This will deal with removing the
1646 timed out packet. */
1647 if(rrec->timeout_fn) {
1648 (*rrec->timeout_fn)(subrec, rrec);
1649 } else {
1650 /* We must remove the record ourself if there is
1651 no timeout function. */
1652 remove_response_record(subrec, rrec);
1654 /* We have changed subrec->responselist,
1655 * restart from the beginning of this list. */
1656 goto restart;
1657 } /* !rrec->in_expitation_processing */
1658 } /* rrec->repeat_count > 0 */
1659 } /* rrec->repeat_time <= t */
1660 } /* end for rrec */
1661 } /* end for subnet */
1664 /****************************************************************************
1665 Create an fd_set containing all the sockets in the subnet structures,
1666 plus the broadcast sockets.
1667 ***************************************************************************/
1669 static bool create_listen_fdset(fd_set **ppset, int **psock_array, int *listen_number, int *maxfd)
1671 int *sock_array = NULL;
1672 struct subnet_record *subrec = NULL;
1673 int count = 0;
1674 int num = 0;
1675 fd_set *pset = SMB_MALLOC_P(fd_set);
1677 if(pset == NULL) {
1678 DEBUG(0,("create_listen_fdset: malloc fail !\n"));
1679 return True;
1682 /* Check that we can add all the fd's we need. */
1683 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1684 count++;
1686 if((count*2) + 2 > FD_SETSIZE) {
1687 DEBUG(0,("create_listen_fdset: Too many file descriptors needed (%d). We can \
1688 only use %d.\n", (count*2) + 2, FD_SETSIZE));
1689 SAFE_FREE(pset);
1690 return True;
1693 if((sock_array = SMB_MALLOC_ARRAY(int, (count*2) + 2)) == NULL) {
1694 DEBUG(0,("create_listen_fdset: malloc fail for socket array.\n"));
1695 SAFE_FREE(pset);
1696 return True;
1699 FD_ZERO(pset);
1701 /* Add in the broadcast socket on 137. */
1702 FD_SET(ClientNMB,pset);
1703 sock_array[num++] = ClientNMB;
1704 *maxfd = MAX( *maxfd, ClientNMB);
1706 /* Add in the 137 sockets on all the interfaces. */
1707 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1708 FD_SET(subrec->nmb_sock,pset);
1709 sock_array[num++] = subrec->nmb_sock;
1710 *maxfd = MAX( *maxfd, subrec->nmb_sock);
1713 /* Add in the broadcast socket on 138. */
1714 FD_SET(ClientDGRAM,pset);
1715 sock_array[num++] = ClientDGRAM;
1716 *maxfd = MAX( *maxfd, ClientDGRAM);
1718 /* Add in the 138 sockets on all the interfaces. */
1719 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1720 FD_SET(subrec->dgram_sock,pset);
1721 sock_array[num++] = subrec->dgram_sock;
1722 *maxfd = MAX( *maxfd, subrec->dgram_sock);
1725 *listen_number = (count*2) + 2;
1727 SAFE_FREE(*ppset);
1728 SAFE_FREE(*psock_array);
1730 *ppset = pset;
1731 *psock_array = sock_array;
1733 return False;
1736 /****************************************************************************
1737 Listens for NMB or DGRAM packets, and queues them.
1738 return True if the socket is dead
1739 ***************************************************************************/
1741 bool listen_for_packets(bool run_election)
1743 static fd_set *listen_set = NULL;
1744 static int listen_number = 0;
1745 static int *sock_array = NULL;
1746 int i;
1747 static int maxfd = 0;
1749 fd_set r_fds;
1750 fd_set w_fds;
1751 int selrtn;
1752 struct timeval timeout;
1753 #ifndef SYNC_DNS
1754 int dns_fd;
1755 #endif
1757 if(listen_set == NULL || rescan_listen_set) {
1758 if(create_listen_fdset(&listen_set, &sock_array, &listen_number, &maxfd)) {
1759 DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
1760 return True;
1762 rescan_listen_set = False;
1765 memcpy((char *)&r_fds, (char *)listen_set, sizeof(fd_set));
1766 FD_ZERO(&w_fds);
1768 #ifndef SYNC_DNS
1769 dns_fd = asyncdns_fd();
1770 if (dns_fd != -1) {
1771 FD_SET(dns_fd, &r_fds);
1772 maxfd = MAX( maxfd, dns_fd);
1774 #endif
1776 /* Process a signal and timer events now... */
1777 if (run_events(nmbd_event_context(), 0, NULL, NULL)) {
1778 return False;
1782 * During elections and when expecting a netbios response packet we
1783 * need to send election packets at tighter intervals.
1784 * Ideally it needs to be the interval (in ms) between time now and
1785 * the time we are expecting the next netbios packet.
1788 timeout.tv_sec = (run_election||num_response_packets) ? 1 : NMBD_SELECT_LOOP;
1789 timeout.tv_usec = 0;
1792 struct timeval now = timeval_current();
1793 event_add_to_select_args(nmbd_event_context(), &now,
1794 &r_fds, &w_fds, &timeout, &maxfd);
1797 selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&timeout);
1799 if (run_events(nmbd_event_context(), selrtn, &r_fds, &w_fds)) {
1800 return False;
1803 if (selrtn == -1) {
1804 return False;
1807 #ifndef SYNC_DNS
1808 if (dns_fd != -1 && FD_ISSET(dns_fd,&r_fds)) {
1809 run_dns_queue();
1811 #endif
1813 for(i = 0; i < listen_number; i++) {
1814 if (i < (listen_number/2)) {
1815 /* Processing a 137 socket. */
1816 if (FD_ISSET(sock_array[i],&r_fds)) {
1817 struct packet_struct *packet = read_packet(sock_array[i], NMB_PACKET);
1818 if (packet) {
1820 * If we got a packet on the broadcast socket and interfaces
1821 * only is set then check it came from one of our local nets.
1823 if(lp_bind_interfaces_only() && (sock_array[i] == ClientNMB) &&
1824 (!is_local_net_v4(packet->ip))) {
1825 DEBUG(7,("discarding nmb packet sent to broadcast socket from %s:%d\n",
1826 inet_ntoa(packet->ip),packet->port));
1827 free_packet(packet);
1828 } else if ((is_loopback_ip_v4(packet->ip) ||
1829 ismyip_v4(packet->ip)) && packet->port == global_nmb_port &&
1830 packet->packet.nmb.header.nm_flags.bcast) {
1831 DEBUG(7,("discarding own bcast packet from %s:%d\n",
1832 inet_ntoa(packet->ip),packet->port));
1833 free_packet(packet);
1834 } else {
1835 /* Save the file descriptor this packet came in on. */
1836 packet->fd = sock_array[i];
1837 queue_packet(packet);
1841 } else {
1842 /* Processing a 138 socket. */
1843 if (FD_ISSET(sock_array[i],&r_fds)) {
1844 struct packet_struct *packet = read_packet(sock_array[i], DGRAM_PACKET);
1845 if (packet) {
1847 * If we got a packet on the broadcast socket and interfaces
1848 * only is set then check it came from one of our local nets.
1850 if(lp_bind_interfaces_only() && (sock_array[i] == ClientDGRAM) &&
1851 (!is_local_net_v4(packet->ip))) {
1852 DEBUG(7,("discarding dgram packet sent to broadcast socket from %s:%d\n",
1853 inet_ntoa(packet->ip),packet->port));
1854 free_packet(packet);
1855 } else if ((is_loopback_ip_v4(packet->ip) ||
1856 ismyip_v4(packet->ip)) && packet->port == DGRAM_PORT) {
1857 DEBUG(7,("discarding own dgram packet from %s:%d\n",
1858 inet_ntoa(packet->ip),packet->port));
1859 free_packet(packet);
1860 } else {
1861 /* Save the file descriptor this packet came in on. */
1862 packet->fd = sock_array[i];
1863 queue_packet(packet);
1867 } /* end processing 138 socket. */
1868 } /* end for */
1869 return False;
1872 /****************************************************************************
1873 Construct and send a netbios DGRAM.
1874 **************************************************************************/
1876 bool send_mailslot(bool unique, const char *mailslot,char *buf, size_t len,
1877 const char *srcname, int src_type,
1878 const char *dstname, int dest_type,
1879 struct in_addr dest_ip,struct in_addr src_ip,
1880 int dest_port)
1882 bool loopback_this_packet = False;
1883 struct packet_struct p;
1884 struct dgram_packet *dgram = &p.packet.dgram;
1885 char *ptr,*p2;
1886 char tmp[4];
1888 memset((char *)&p,'\0',sizeof(p));
1890 if(ismyip_v4(dest_ip) && (dest_port == DGRAM_PORT)) /* Only if to DGRAM_PORT */
1891 loopback_this_packet = True;
1893 /* generate_name_trn_id(); */ /* Not used, so gone, RJS */
1895 /* DIRECT GROUP or UNIQUE datagram. */
1896 dgram->header.msg_type = unique ? 0x10 : 0x11;
1897 dgram->header.flags.node_type = M_NODE;
1898 dgram->header.flags.first = True;
1899 dgram->header.flags.more = False;
1900 dgram->header.dgm_id = generate_name_trn_id();
1901 dgram->header.source_ip = src_ip;
1902 dgram->header.source_port = DGRAM_PORT;
1903 dgram->header.dgm_length = 0; /* Let build_dgram() handle this. */
1904 dgram->header.packet_offset = 0;
1906 make_nmb_name(&dgram->source_name,srcname,src_type);
1907 make_nmb_name(&dgram->dest_name,dstname,dest_type);
1909 ptr = &dgram->data[0];
1911 /* Setup the smb part. */
1912 ptr -= 4; /* XXX Ugliness because of handling of tcp SMB length. */
1913 memcpy(tmp,ptr,4);
1915 if (smb_size + 17*2 + strlen(mailslot) + 1 + len > MAX_DGRAM_SIZE) {
1916 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
1917 return false;
1920 cli_set_message(ptr,17,strlen(mailslot) + 1 + len,True);
1921 memcpy(ptr,tmp,4);
1923 SCVAL(ptr,smb_com,SMBtrans);
1924 SSVAL(ptr,smb_vwv1,len);
1925 SSVAL(ptr,smb_vwv11,len);
1926 SSVAL(ptr,smb_vwv12,70 + strlen(mailslot));
1927 SSVAL(ptr,smb_vwv13,3);
1928 SSVAL(ptr,smb_vwv14,1);
1929 SSVAL(ptr,smb_vwv15,1);
1930 SSVAL(ptr,smb_vwv16,2);
1931 p2 = smb_buf(ptr);
1932 safe_strcpy_base(p2, mailslot, dgram->data, sizeof(dgram->data));
1933 p2 = skip_string(ptr,MAX_DGRAM_SIZE,p2);
1935 if (((p2+len) > dgram->data+sizeof(dgram->data)) || ((p2+len) < p2)) {
1936 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
1937 return False;
1938 } else {
1939 memcpy(p2,buf,len);
1940 p2 += len;
1943 dgram->datasize = PTR_DIFF(p2,ptr+4); /* +4 for tcp length. */
1945 p.ip = dest_ip;
1946 p.port = dest_port;
1947 p.fd = find_subnet_mailslot_fd_for_address( src_ip );
1948 p.timestamp = time(NULL);
1949 p.packet_type = DGRAM_PACKET;
1951 DEBUG(4,("send_mailslot: Sending to mailslot %s from %s IP %s ", mailslot,
1952 nmb_namestr(&dgram->source_name), inet_ntoa(src_ip)));
1953 DEBUG(4,("to %s IP %s\n", nmb_namestr(&dgram->dest_name), inet_ntoa(dest_ip)));
1955 debug_browse_data(buf, len);
1957 if(loopback_this_packet) {
1958 struct packet_struct *lo_packet = NULL;
1959 DEBUG(5,("send_mailslot: sending packet to ourselves.\n"));
1960 if((lo_packet = copy_packet(&p)) == NULL)
1961 return False;
1962 queue_packet(lo_packet);
1963 return True;
1964 } else {
1965 return(send_packet(&p));