s3-security: use shared SECINFO_SACL define.
[Samba/ekacnet.git] / source3 / nmbd / nmbd_packets.c
blob8e46efe2d06a0cab6c6d47a7bc55124b69c61d9f
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->recv_fd = -1;
211 packet->send_fd = ClientNMB;
212 packet->timestamp = time(NULL);
213 packet->packet_type = NMB_PACKET;
214 packet->locked = False;
216 return packet; /* Caller must free. */
219 /***************************************************************************
220 Sets up the common elements of register, refresh or release packet.
221 **************************************************************************/
223 static bool create_and_init_additional_record(struct packet_struct *packet,
224 uint16 nb_flags,
225 const struct in_addr *register_ip)
227 struct nmb_packet *nmb = &packet->packet.nmb;
229 if((nmb->additional = SMB_MALLOC_P(struct res_rec)) == NULL) {
230 DEBUG(0,("create_and_init_additional_record: malloc fail for additional record.\n"));
231 return False;
234 memset((char *)nmb->additional,'\0',sizeof(struct res_rec));
236 nmb->additional->rr_name = nmb->question.question_name;
237 nmb->additional->rr_type = RR_TYPE_NB;
238 nmb->additional->rr_class = RR_CLASS_IN;
240 /* See RFC 1002, sections 5.1.1.1, 5.1.1.2 and 5.1.1.3 */
241 if (nmb->header.nm_flags.bcast)
242 nmb->additional->ttl = PERMANENT_TTL;
243 else
244 nmb->additional->ttl = lp_max_ttl();
246 nmb->additional->rdlength = 6;
248 set_nb_flags(nmb->additional->rdata,nb_flags);
250 /* Set the address for the name we are registering. */
251 putip(&nmb->additional->rdata[2], register_ip);
254 it turns out that Jeremys code was correct, we are supposed
255 to send registrations from the IP we are registering. The
256 trick is what to do on timeouts! When we send on a
257 non-routable IP then the reply will timeout, and we should
258 treat this as success, not failure. That means we go into
259 our standard refresh cycle for that name which copes nicely
260 with disconnected networks.
262 packet->recv_fd = -1;
263 packet->send_fd = find_subnet_fd_for_address(*register_ip);
265 return True;
268 /***************************************************************************
269 Sends out a name query.
270 **************************************************************************/
272 static bool initiate_name_query_packet( struct packet_struct *packet)
274 struct nmb_packet *nmb = NULL;
276 nmb = &packet->packet.nmb;
278 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
279 nmb->header.arcount = 0;
281 nmb->header.nm_flags.recursion_desired = True;
283 DEBUG(4,("initiate_name_query_packet: sending query for name %s (bcast=%s) to IP %s\n",
284 nmb_namestr(&nmb->question.question_name),
285 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
287 return send_netbios_packet( packet );
290 /***************************************************************************
291 Sends out a name query - from a WINS server.
292 **************************************************************************/
294 static bool initiate_name_query_packet_from_wins_server( struct packet_struct *packet)
296 struct nmb_packet *nmb = NULL;
298 nmb = &packet->packet.nmb;
300 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
301 nmb->header.arcount = 0;
303 nmb->header.nm_flags.recursion_desired = False;
305 DEBUG(4,("initiate_name_query_packet_from_wins_server: sending query for name %s (bcast=%s) to IP %s\n",
306 nmb_namestr(&nmb->question.question_name),
307 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
309 return send_netbios_packet( packet );
312 /***************************************************************************
313 Sends out a name register.
314 **************************************************************************/
316 static bool initiate_name_register_packet( struct packet_struct *packet,
317 uint16 nb_flags, const struct in_addr *register_ip)
319 struct nmb_packet *nmb = &packet->packet.nmb;
321 nmb->header.opcode = NMB_NAME_REG_OPCODE;
322 nmb->header.arcount = 1;
324 nmb->header.nm_flags.recursion_desired = True;
326 if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
327 return False;
329 DEBUG(4,("initiate_name_register_packet: sending registration for name %s (bcast=%s) to IP %s\n",
330 nmb_namestr(&nmb->additional->rr_name),
331 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
333 return send_netbios_packet( packet );
336 /***************************************************************************
337 Sends out a multihomed name register.
338 **************************************************************************/
340 static bool initiate_multihomed_name_register_packet(struct packet_struct *packet,
341 uint16 nb_flags, struct in_addr *register_ip)
343 struct nmb_packet *nmb = &packet->packet.nmb;
344 fstring second_ip_buf;
346 fstrcpy(second_ip_buf, inet_ntoa(packet->ip));
348 nmb->header.opcode = NMB_NAME_MULTIHOMED_REG_OPCODE;
349 nmb->header.arcount = 1;
351 nmb->header.nm_flags.recursion_desired = True;
353 if(create_and_init_additional_record(packet, nb_flags, register_ip) == False)
354 return False;
356 DEBUG(4,("initiate_multihomed_name_register_packet: sending registration \
357 for name %s IP %s (bcast=%s) to IP %s\n",
358 nmb_namestr(&nmb->additional->rr_name), inet_ntoa(*register_ip),
359 BOOLSTR(nmb->header.nm_flags.bcast), second_ip_buf ));
361 return send_netbios_packet( packet );
364 /***************************************************************************
365 Sends out a name refresh.
366 **************************************************************************/
368 static bool initiate_name_refresh_packet( struct packet_struct *packet,
369 uint16 nb_flags, struct in_addr *refresh_ip)
371 struct nmb_packet *nmb = &packet->packet.nmb;
373 nmb->header.opcode = NMB_NAME_REFRESH_OPCODE_8;
374 nmb->header.arcount = 1;
376 nmb->header.nm_flags.recursion_desired = False;
378 if(create_and_init_additional_record(packet, nb_flags, refresh_ip) == False)
379 return False;
381 DEBUG(4,("initiate_name_refresh_packet: sending refresh for name %s (bcast=%s) to IP %s\n",
382 nmb_namestr(&nmb->additional->rr_name),
383 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
385 return send_netbios_packet( packet );
388 /***************************************************************************
389 Sends out a name release.
390 **************************************************************************/
392 static bool initiate_name_release_packet( struct packet_struct *packet,
393 uint16 nb_flags, struct in_addr *release_ip)
395 struct nmb_packet *nmb = &packet->packet.nmb;
397 nmb->header.opcode = NMB_NAME_RELEASE_OPCODE;
398 nmb->header.arcount = 1;
400 nmb->header.nm_flags.recursion_desired = False;
402 if(create_and_init_additional_record(packet, nb_flags, release_ip) == False)
403 return False;
405 DEBUG(4,("initiate_name_release_packet: sending release for name %s (bcast=%s) to IP %s\n",
406 nmb_namestr(&nmb->additional->rr_name),
407 BOOLSTR(nmb->header.nm_flags.bcast), inet_ntoa(packet->ip)));
409 return send_netbios_packet( packet );
412 /***************************************************************************
413 Sends out a node status.
414 **************************************************************************/
416 static bool initiate_node_status_packet( struct packet_struct *packet )
418 struct nmb_packet *nmb = &packet->packet.nmb;
420 nmb->header.opcode = NMB_NAME_QUERY_OPCODE;
421 nmb->header.arcount = 0;
423 nmb->header.nm_flags.recursion_desired = False;
425 nmb->question.question_type = QUESTION_TYPE_NB_STATUS;
427 DEBUG(4,("initiate_node_status_packet: sending node status request for name %s to IP %s\n",
428 nmb_namestr(&nmb->question.question_name),
429 inet_ntoa(packet->ip)));
431 return send_netbios_packet( packet );
434 /****************************************************************************
435 Simplification functions for queuing standard packets.
436 These should be the only publicly callable functions for sending
437 out packets.
438 ****************************************************************************/
440 /****************************************************************************
441 Assertion - we should never be sending nmbd packets on the remote
442 broadcast subnet.
443 ****************************************************************************/
445 static bool assert_check_subnet(struct subnet_record *subrec)
447 if( subrec == remote_broadcast_subnet) {
448 DEBUG(0,("assert_check_subnet: Attempt to send packet on remote broadcast subnet. \
449 This is a bug.\n"));
450 return True;
452 return False;
455 /****************************************************************************
456 Queue a register name packet to the broadcast address of a subnet.
457 ****************************************************************************/
459 struct response_record *queue_register_name( struct subnet_record *subrec,
460 response_function resp_fn,
461 timeout_response_function timeout_fn,
462 register_name_success_function success_fn,
463 register_name_fail_function fail_fn,
464 struct userdata_struct *userdata,
465 struct nmb_name *nmbname,
466 uint16 nb_flags)
468 struct packet_struct *p;
469 struct response_record *rrec;
470 struct sockaddr_storage ss;
471 const struct sockaddr_storage *pss = NULL;
472 if(assert_check_subnet(subrec))
473 return NULL;
475 /* note that all name registration requests have RD set (rfc1002 - section 4.2.2 */
476 if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), True,
477 subrec->bcast_ip)) == NULL)
478 return NULL;
480 in_addr_to_sockaddr_storage(&ss, subrec->bcast_ip);
481 pss = iface_ip((struct sockaddr *)&ss);
482 if (!pss || pss->ss_family != AF_INET) {
483 p->locked = False;
484 free_packet(p);
485 return NULL;
488 if(initiate_name_register_packet(p, nb_flags,
489 &((const struct sockaddr_in *)pss)->sin_addr) == False) {
490 p->locked = False;
491 free_packet(p);
492 return NULL;
495 if((rrec = make_response_record(subrec, /* subnet record. */
496 p, /* packet we sent. */
497 resp_fn, /* function to call on response. */
498 timeout_fn, /* function to call on timeout. */
499 (success_function)success_fn, /* function to call on operation success. */
500 (fail_function)fail_fn, /* function to call on operation fail. */
501 userdata)) == NULL) {
502 p->locked = False;
503 free_packet(p);
504 return NULL;
507 return rrec;
510 /****************************************************************************
511 Queue a refresh name packet to the broadcast address of a subnet.
512 ****************************************************************************/
514 void queue_wins_refresh(struct nmb_name *nmbname,
515 response_function resp_fn,
516 timeout_response_function timeout_fn,
517 uint16 nb_flags,
518 struct in_addr refresh_ip,
519 const char *tag)
521 struct packet_struct *p;
522 struct response_record *rrec;
523 struct in_addr wins_ip;
524 struct userdata_struct *userdata;
525 fstring ip_str;
527 wins_ip = wins_srv_ip_tag(tag, refresh_ip);
529 if ((p = create_and_init_netbios_packet(nmbname, False, False, wins_ip)) == NULL) {
530 return;
533 if (!initiate_name_refresh_packet(p, nb_flags, &refresh_ip)) {
534 p->locked = False;
535 free_packet(p);
536 return;
539 fstrcpy(ip_str, inet_ntoa(refresh_ip));
541 DEBUG(6,("Refreshing name %s IP %s with WINS server %s using tag '%s'\n",
542 nmb_namestr(nmbname), ip_str, inet_ntoa(wins_ip), tag));
544 userdata = (struct userdata_struct *)SMB_MALLOC(sizeof(*userdata) + strlen(tag) + 1);
545 if (!userdata) {
546 p->locked = False;
547 free_packet(p);
548 DEBUG(0,("Failed to allocate userdata structure!\n"));
549 return;
551 ZERO_STRUCTP(userdata);
552 userdata->userdata_len = strlen(tag) + 1;
553 strlcpy(userdata->data, tag, userdata->userdata_len);
555 if ((rrec = make_response_record(unicast_subnet,
557 resp_fn, timeout_fn,
558 NULL,
559 NULL,
560 userdata)) == NULL) {
561 p->locked = False;
562 free_packet(p);
563 return;
566 free(userdata);
568 /* we don't want to repeat refresh packets */
569 rrec->repeat_count = 0;
573 /****************************************************************************
574 Queue a multihomed register name packet to a given WINS server IP
575 ****************************************************************************/
577 struct response_record *queue_register_multihomed_name( struct subnet_record *subrec,
578 response_function resp_fn,
579 timeout_response_function timeout_fn,
580 register_name_success_function success_fn,
581 register_name_fail_function fail_fn,
582 struct userdata_struct *userdata,
583 struct nmb_name *nmbname,
584 uint16 nb_flags,
585 struct in_addr register_ip,
586 struct in_addr wins_ip)
588 struct packet_struct *p;
589 struct response_record *rrec;
590 bool ret;
592 /* Sanity check. */
593 if(subrec != unicast_subnet) {
594 DEBUG(0,("queue_register_multihomed_name: should only be done on \
595 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
596 return NULL;
599 if(assert_check_subnet(subrec))
600 return NULL;
602 if ((p = create_and_init_netbios_packet(nmbname, False, True, wins_ip)) == NULL)
603 return NULL;
605 if (nb_flags & NB_GROUP)
606 ret = initiate_name_register_packet( p, nb_flags, &register_ip);
607 else
608 ret = initiate_multihomed_name_register_packet(p, nb_flags, &register_ip);
610 if (ret == False) {
611 p->locked = False;
612 free_packet(p);
613 return NULL;
616 if ((rrec = make_response_record(subrec, /* subnet record. */
617 p, /* packet we sent. */
618 resp_fn, /* function to call on response. */
619 timeout_fn, /* function to call on timeout. */
620 (success_function)success_fn, /* function to call on operation success. */
621 (fail_function)fail_fn, /* function to call on operation fail. */
622 userdata)) == NULL) {
623 p->locked = False;
624 free_packet(p);
625 return NULL;
628 return rrec;
631 /****************************************************************************
632 Queue a release name packet to the broadcast address of a subnet.
633 ****************************************************************************/
635 struct response_record *queue_release_name( struct subnet_record *subrec,
636 response_function resp_fn,
637 timeout_response_function timeout_fn,
638 release_name_success_function success_fn,
639 release_name_fail_function fail_fn,
640 struct userdata_struct *userdata,
641 struct nmb_name *nmbname,
642 uint16 nb_flags,
643 struct in_addr release_ip,
644 struct in_addr dest_ip)
646 struct packet_struct *p;
647 struct response_record *rrec;
649 if(assert_check_subnet(subrec))
650 return NULL;
652 if ((p = create_and_init_netbios_packet(nmbname, (subrec != unicast_subnet), False, dest_ip)) == NULL)
653 return NULL;
655 if(initiate_name_release_packet( p, nb_flags, &release_ip) == False) {
656 p->locked = False;
657 free_packet(p);
658 return NULL;
661 if((rrec = make_response_record(subrec, /* subnet record. */
662 p, /* packet we sent. */
663 resp_fn, /* function to call on response. */
664 timeout_fn, /* function to call on timeout. */
665 (success_function)success_fn, /* function to call on operation success. */
666 (fail_function)fail_fn, /* function to call on operation fail. */
667 userdata)) == NULL) {
668 p->locked = False;
669 free_packet(p);
670 return NULL;
674 * For a broadcast release packet, only send once.
675 * This will cause us to remove the name asap. JRA.
678 if (subrec != unicast_subnet) {
679 rrec->repeat_count = 0;
680 rrec->repeat_time = 0;
683 return rrec;
686 /****************************************************************************
687 Queue a query name packet to the broadcast address of a subnet.
688 ****************************************************************************/
690 struct response_record *queue_query_name( struct subnet_record *subrec,
691 response_function resp_fn,
692 timeout_response_function timeout_fn,
693 query_name_success_function success_fn,
694 query_name_fail_function fail_fn,
695 struct userdata_struct *userdata,
696 struct nmb_name *nmbname)
698 struct packet_struct *p;
699 struct response_record *rrec;
700 struct in_addr to_ip;
702 if(assert_check_subnet(subrec))
703 return NULL;
705 to_ip = subrec->bcast_ip;
707 /* queries to the WINS server turn up here as queries to IP 0.0.0.0
708 These need to be handled a bit differently */
709 if (subrec->type == UNICAST_SUBNET && is_zero_ip_v4(to_ip)) {
710 /* What we really need to do is loop over each of our wins
711 * servers and wins server tags here, but that just doesn't
712 * fit our architecture at the moment (userdata may already
713 * be used when we get here). For now we just query the first
714 * active wins server on the first tag.
716 char **tags = wins_srv_tags();
717 if (!tags) {
718 return NULL;
720 to_ip = wins_srv_ip_tag(tags[0], to_ip);
721 wins_srv_tags_free(tags);
724 if(( p = create_and_init_netbios_packet(nmbname,
725 (subrec != unicast_subnet),
726 (subrec == unicast_subnet),
727 to_ip)) == NULL)
728 return NULL;
730 if(lp_bind_interfaces_only()) {
731 int i;
733 DEBUG(10,("queue_query_name: bind_interfaces_only is set, looking for suitable source IP\n"));
734 for(i = 0; i < iface_count(); i++) {
735 const struct in_addr *ifip = iface_n_ip_v4(i);
737 if (ifip == NULL) {
738 DEBUG(0,("queue_query_name: interface %d has NULL IP address !\n", i));
739 continue;
742 if (is_loopback_ip_v4(*ifip)) {
743 DEBUG(5,("queue_query_name: ignoring loopback interface (%d)\n", i));
744 continue;
747 DEBUG(10,("queue_query_name: using source IP %s\n",inet_ntoa(*ifip)));
748 p->send_fd = find_subnet_fd_for_address( *ifip );
749 break;
753 if(initiate_name_query_packet( p ) == False) {
754 p->locked = False;
755 free_packet(p);
756 return NULL;
759 if((rrec = make_response_record(subrec, /* subnet record. */
760 p, /* packet we sent. */
761 resp_fn, /* function to call on response. */
762 timeout_fn, /* function to call on timeout. */
763 (success_function)success_fn, /* function to call on operation success. */
764 (fail_function)fail_fn, /* function to call on operation fail. */
765 userdata)) == NULL) {
766 p->locked = False;
767 free_packet(p);
768 return NULL;
771 return rrec;
774 /****************************************************************************
775 Queue a query name packet to a given address from the WINS subnet.
776 ****************************************************************************/
778 struct response_record *queue_query_name_from_wins_server( struct in_addr to_ip,
779 response_function resp_fn,
780 timeout_response_function timeout_fn,
781 query_name_success_function success_fn,
782 query_name_fail_function fail_fn,
783 struct userdata_struct *userdata,
784 struct nmb_name *nmbname)
786 struct packet_struct *p;
787 struct response_record *rrec;
789 if ((p = create_and_init_netbios_packet(nmbname, False, False, to_ip)) == NULL)
790 return NULL;
792 if(initiate_name_query_packet_from_wins_server( p ) == False) {
793 p->locked = False;
794 free_packet(p);
795 return NULL;
798 if((rrec = make_response_record(wins_server_subnet, /* subnet record. */
799 p, /* packet we sent. */
800 resp_fn, /* function to call on response. */
801 timeout_fn, /* function to call on timeout. */
802 (success_function)success_fn, /* function to call on operation success. */
803 (fail_function)fail_fn, /* function to call on operation fail. */
804 userdata)) == NULL) {
805 p->locked = False;
806 free_packet(p);
807 return NULL;
810 return rrec;
813 /****************************************************************************
814 Queue a node status packet to a given name and address.
815 ****************************************************************************/
817 struct response_record *queue_node_status( struct subnet_record *subrec,
818 response_function resp_fn,
819 timeout_response_function timeout_fn,
820 node_status_success_function success_fn,
821 node_status_fail_function fail_fn,
822 struct userdata_struct *userdata,
823 struct nmb_name *nmbname,
824 struct in_addr send_ip)
826 struct packet_struct *p;
827 struct response_record *rrec;
829 /* Sanity check. */
830 if(subrec != unicast_subnet) {
831 DEBUG(0,("queue_register_multihomed_name: should only be done on \
832 unicast subnet. subnet is %s\n.", subrec->subnet_name ));
833 return NULL;
836 if(assert_check_subnet(subrec))
837 return NULL;
839 if(( p = create_and_init_netbios_packet(nmbname, False, False, send_ip)) == NULL)
840 return NULL;
842 if(initiate_node_status_packet(p) == False) {
843 p->locked = False;
844 free_packet(p);
845 return NULL;
848 if((rrec = make_response_record(subrec, /* subnet record. */
849 p, /* packet we sent. */
850 resp_fn, /* function to call on response. */
851 timeout_fn, /* function to call on timeout. */
852 (success_function)success_fn, /* function to call on operation success. */
853 (fail_function)fail_fn, /* function to call on operation fail. */
854 userdata)) == NULL) {
855 p->locked = False;
856 free_packet(p);
857 return NULL;
860 return rrec;
863 /****************************************************************************
864 Reply to a netbios name packet. see rfc1002.txt
865 ****************************************************************************/
867 void reply_netbios_packet(struct packet_struct *orig_packet,
868 int rcode, enum netbios_reply_type_code rcv_code, int opcode,
869 int ttl, char *data,int len)
871 struct packet_struct packet;
872 struct nmb_packet *nmb = NULL;
873 struct res_rec answers;
874 struct nmb_packet *orig_nmb = &orig_packet->packet.nmb;
875 bool loopback_this_packet = False;
876 int rr_type = RR_TYPE_NB;
877 const char *packet_type = "unknown";
879 /* Check if we are sending to or from ourselves. */
880 if(ismyip_v4(orig_packet->ip) && (orig_packet->port == global_nmb_port))
881 loopback_this_packet = True;
883 nmb = &packet.packet.nmb;
885 /* Do a partial copy of the packet. We clear the locked flag and
886 the resource record pointers. */
887 packet = *orig_packet; /* Full structure copy. */
888 packet.locked = False;
889 nmb->answers = NULL;
890 nmb->nsrecs = NULL;
891 nmb->additional = NULL;
893 switch (rcv_code) {
894 case NMB_STATUS:
895 packet_type = "nmb_status";
896 nmb->header.nm_flags.recursion_desired = False;
897 nmb->header.nm_flags.recursion_available = False;
898 rr_type = RR_TYPE_NBSTAT;
899 break;
900 case NMB_QUERY:
901 packet_type = "nmb_query";
902 nmb->header.nm_flags.recursion_desired = True;
903 nmb->header.nm_flags.recursion_available = True;
904 if (rcode) {
905 rr_type = RR_TYPE_NULL;
907 break;
908 case NMB_REG:
909 case NMB_REG_REFRESH:
910 packet_type = "nmb_reg";
911 nmb->header.nm_flags.recursion_desired = True;
912 nmb->header.nm_flags.recursion_available = True;
913 break;
914 case NMB_REL:
915 packet_type = "nmb_rel";
916 nmb->header.nm_flags.recursion_desired = False;
917 nmb->header.nm_flags.recursion_available = False;
918 break;
919 case NMB_WAIT_ACK:
920 packet_type = "nmb_wack";
921 nmb->header.nm_flags.recursion_desired = False;
922 nmb->header.nm_flags.recursion_available = False;
923 rr_type = RR_TYPE_NULL;
924 break;
925 case WINS_REG:
926 packet_type = "wins_reg";
927 nmb->header.nm_flags.recursion_desired = True;
928 nmb->header.nm_flags.recursion_available = True;
929 break;
930 case WINS_QUERY:
931 packet_type = "wins_query";
932 nmb->header.nm_flags.recursion_desired = True;
933 nmb->header.nm_flags.recursion_available = True;
934 if (rcode) {
935 rr_type = RR_TYPE_NULL;
937 break;
938 default:
939 DEBUG(0,("reply_netbios_packet: Unknown packet type: %s %s to ip %s\n",
940 packet_type, nmb_namestr(&orig_nmb->question.question_name),
941 inet_ntoa(packet.ip)));
942 return;
945 DEBUG(4,("reply_netbios_packet: sending a reply of packet type: %s %s to ip %s \
946 for id %hu\n", packet_type, nmb_namestr(&orig_nmb->question.question_name),
947 inet_ntoa(packet.ip), orig_nmb->header.name_trn_id));
949 nmb->header.name_trn_id = orig_nmb->header.name_trn_id;
950 nmb->header.opcode = opcode;
951 nmb->header.response = True;
952 nmb->header.nm_flags.bcast = False;
953 nmb->header.nm_flags.trunc = False;
954 nmb->header.nm_flags.authoritative = True;
956 nmb->header.rcode = rcode;
957 nmb->header.qdcount = 0;
958 nmb->header.ancount = 1;
959 nmb->header.nscount = 0;
960 nmb->header.arcount = 0;
962 memset((char*)&nmb->question,'\0',sizeof(nmb->question));
964 nmb->answers = &answers;
965 memset((char*)nmb->answers,'\0',sizeof(*nmb->answers));
967 nmb->answers->rr_name = orig_nmb->question.question_name;
968 nmb->answers->rr_type = rr_type;
969 nmb->answers->rr_class = RR_CLASS_IN;
970 nmb->answers->ttl = ttl;
972 if (data && len) {
973 if (len < 0 || len > sizeof(nmb->answers->rdata)) {
974 DEBUG(5,("reply_netbios_packet: "
975 "invalid packet len (%d)\n",
976 len ));
977 return;
979 nmb->answers->rdlength = len;
980 memcpy(nmb->answers->rdata, data, len);
983 packet.packet_type = NMB_PACKET;
984 packet.recv_fd = -1;
985 /* Ensure we send out on the same fd that the original
986 packet came in on to give the correct source IP address. */
987 if (orig_packet->send_fd != -1) {
988 packet.send_fd = orig_packet->send_fd;
989 } else {
990 packet.send_fd = orig_packet->recv_fd;
992 packet.timestamp = time(NULL);
994 debug_nmb_packet(&packet);
996 if(loopback_this_packet) {
997 struct packet_struct *lo_packet;
998 DEBUG(5,("reply_netbios_packet: sending packet to ourselves.\n"));
999 if((lo_packet = copy_packet(&packet)) == NULL)
1000 return;
1001 queue_packet(lo_packet);
1002 } else if (!send_packet(&packet)) {
1003 DEBUG(0,("reply_netbios_packet: send_packet to IP %s port %d failed\n",
1004 inet_ntoa(packet.ip),packet.port));
1008 /*******************************************************************
1009 Queue a packet into a packet queue
1010 ******************************************************************/
1012 void queue_packet(struct packet_struct *packet)
1014 DLIST_ADD_END(packet_queue, packet, struct packet_struct *);
1017 /****************************************************************************
1018 Try and find a matching subnet record for a datagram port 138 packet.
1019 ****************************************************************************/
1021 static struct subnet_record *find_subnet_for_dgram_browse_packet(struct packet_struct *p)
1023 struct subnet_record *subrec;
1025 /* Go through all the broadcast subnets and see if the mask matches. */
1026 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1027 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1028 return subrec;
1031 /* If the subnet record is the remote announce broadcast subnet,
1032 hack it here to be the first subnet. This is really gross and
1033 is needed due to people turning on port 137/138 broadcast
1034 forwarding on their routers. May fire and brimstone rain
1035 down upon them...
1038 return FIRST_SUBNET;
1041 /****************************************************************************
1042 Dispatch a browse frame from port 138 to the correct processing function.
1043 ****************************************************************************/
1045 static void process_browse_packet(struct packet_struct *p, char *buf,int len)
1047 struct dgram_packet *dgram = &p->packet.dgram;
1048 int command = CVAL(buf,0);
1049 struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1050 char scope[64];
1051 unstring src_name;
1053 /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1054 pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1055 if (!strequal(scope, global_scope())) {
1056 DEBUG(7,("process_browse_packet: Discarding datagram from IP %s. Scope (%s) \
1057 mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
1058 return;
1061 pull_ascii_nstring(src_name, sizeof(src_name), dgram->source_name.name);
1062 if (is_myname(src_name)) {
1063 DEBUG(7,("process_browse_packet: Discarding datagram from IP %s. Source name \
1064 %s is one of our names !\n", inet_ntoa(p->ip), nmb_namestr(&dgram->source_name)));
1065 return;
1068 switch (command) {
1069 case ANN_HostAnnouncement:
1070 debug_browse_data(buf, len);
1071 process_host_announce(subrec, p, buf+1);
1072 break;
1073 case ANN_DomainAnnouncement:
1074 debug_browse_data(buf, len);
1075 process_workgroup_announce(subrec, p, buf+1);
1076 break;
1077 case ANN_LocalMasterAnnouncement:
1078 debug_browse_data(buf, len);
1079 process_local_master_announce(subrec, p, buf+1);
1080 break;
1081 case ANN_AnnouncementRequest:
1082 debug_browse_data(buf, len);
1083 process_announce_request(subrec, p, buf+1);
1084 break;
1085 case ANN_Election:
1086 debug_browse_data(buf, len);
1087 process_election(subrec, p, buf+1);
1088 break;
1089 case ANN_GetBackupListReq:
1090 debug_browse_data(buf, len);
1091 process_get_backup_list_request(subrec, p, buf+1);
1092 break;
1093 case ANN_GetBackupListResp:
1094 debug_browse_data(buf, len);
1095 /* We never send ANN_GetBackupListReq so we should never get these. */
1096 DEBUG(0,("process_browse_packet: Discarding GetBackupListResponse \
1097 packet from %s IP %s\n", nmb_namestr(&dgram->source_name), inet_ntoa(p->ip)));
1098 break;
1099 case ANN_ResetBrowserState:
1100 debug_browse_data(buf, len);
1101 process_reset_browser(subrec, p, buf+1);
1102 break;
1103 case ANN_MasterAnnouncement:
1104 /* Master browser datagrams must be processed on the unicast subnet. */
1105 subrec = unicast_subnet;
1107 debug_browse_data(buf, len);
1108 process_master_browser_announce(subrec, p, buf+1);
1109 break;
1110 case ANN_BecomeBackup:
1112 * We don't currently implement this. Log it just in case.
1114 debug_browse_data(buf, len);
1115 DEBUG(10,("process_browse_packet: On subnet %s ignoring browse packet \
1116 command ANN_BecomeBackup from %s IP %s to %s\n", subrec->subnet_name, nmb_namestr(&dgram->source_name),
1117 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1118 break;
1119 default:
1120 debug_browse_data(buf, len);
1121 DEBUG(0,("process_browse_packet: On subnet %s ignoring browse packet \
1122 command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namestr(&dgram->source_name),
1123 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1124 break;
1128 /****************************************************************************
1129 Dispatch a LanMan browse frame from port 138 to the correct processing function.
1130 ****************************************************************************/
1132 static void process_lanman_packet(struct packet_struct *p, char *buf,int len)
1134 struct dgram_packet *dgram = &p->packet.dgram;
1135 int command = SVAL(buf,0);
1136 struct subnet_record *subrec = find_subnet_for_dgram_browse_packet(p);
1137 char scope[64];
1138 unstring src_name;
1140 /* Drop the packet if it's a different NetBIOS scope, or the source is from one of our names. */
1142 pull_ascii(scope, dgram->dest_name.scope, 64, 64, STR_TERMINATE);
1143 if (!strequal(scope, global_scope())) {
1144 DEBUG(7,("process_lanman_packet: Discarding datagram from IP %s. Scope (%s) \
1145 mismatch with our scope (%s).\n", inet_ntoa(p->ip), scope, global_scope()));
1146 return;
1149 pull_ascii_nstring(src_name, sizeof(src_name), dgram->source_name.name);
1150 if (is_myname(src_name)) {
1151 DEBUG(0,("process_lanman_packet: Discarding datagram from IP %s. Source name \
1152 %s is one of our names !\n", inet_ntoa(p->ip), nmb_namestr(&dgram->source_name)));
1153 return;
1156 switch (command) {
1157 case ANN_HostAnnouncement:
1158 debug_browse_data(buf, len);
1159 process_lm_host_announce(subrec, p, buf+1, len > 1 ? len-1 : 0);
1160 break;
1161 case ANN_AnnouncementRequest:
1162 process_lm_announce_request(subrec, p, buf+1, len > 1 ? len-1 : 0);
1163 break;
1164 default:
1165 DEBUG(0,("process_lanman_packet: On subnet %s ignoring browse packet \
1166 command code %d from %s IP %s to %s\n", subrec->subnet_name, command, nmb_namestr(&dgram->source_name),
1167 inet_ntoa(p->ip), nmb_namestr(&dgram->dest_name)));
1168 break;
1172 /****************************************************************************
1173 Determine if a packet is for us on port 138. Note that to have any chance of
1174 being efficient we need to drop as many packets as possible at this
1175 stage as subsequent processing is expensive.
1176 ****************************************************************************/
1178 static bool listening(struct packet_struct *p,struct nmb_name *nbname)
1180 struct subnet_record *subrec = NULL;
1182 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1183 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1184 break;
1187 if(subrec == NULL)
1188 subrec = unicast_subnet;
1190 return (find_name_on_subnet(subrec, nbname, FIND_SELF_NAME) != NULL);
1193 /****************************************************************************
1194 Process udp 138 datagrams
1195 ****************************************************************************/
1197 static void process_dgram(struct packet_struct *p)
1199 char *buf;
1200 char *buf2;
1201 int len;
1202 struct dgram_packet *dgram = &p->packet.dgram;
1204 /* If we aren't listening to the destination name then ignore the packet */
1205 if (!listening(p,&dgram->dest_name)) {
1206 unexpected_packet(p);
1207 DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from %s\n",
1208 nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip)));
1209 return;
1212 if (dgram->header.msg_type != 0x10 && dgram->header.msg_type != 0x11 && dgram->header.msg_type != 0x12) {
1213 unexpected_packet(p);
1214 /* Don't process error packets etc yet */
1215 DEBUG(5,("process_dgram: ignoring dgram packet sent to name %s from IP %s as it is \
1216 an error packet of type %x\n", nmb_namestr(&dgram->dest_name), inet_ntoa(p->ip), dgram->header.msg_type));
1217 return;
1220 /* Ensure we have a large enough packet before looking inside. */
1221 if (dgram->datasize < (smb_vwv12 - 2)) {
1222 /* That's the offset minus the 4 byte length + 2 bytes of offset. */
1223 DEBUG(0,("process_dgram: ignoring too short dgram packet (%u) sent to name %s from IP %s\n",
1224 (unsigned int)dgram->datasize,
1225 nmb_namestr(&dgram->dest_name),
1226 inet_ntoa(p->ip) ));
1227 return;
1230 buf = &dgram->data[0];
1231 buf -= 4; /* XXXX for the pseudo tcp length - someday I need to get rid of this */
1233 if (CVAL(buf,smb_com) != SMBtrans)
1234 return;
1236 len = SVAL(buf,smb_vwv11);
1237 buf2 = smb_base(buf) + SVAL(buf,smb_vwv12);
1239 if (len <= 0 || len > dgram->datasize) {
1240 DEBUG(0,("process_dgram: ignoring malformed1 (datasize = %d, len = %d) datagram \
1241 packet sent to name %s from IP %s\n",
1242 dgram->datasize,
1243 len,
1244 nmb_namestr(&dgram->dest_name),
1245 inet_ntoa(p->ip) ));
1246 return;
1249 if (buf2 < dgram->data || (buf2 >= dgram->data + dgram->datasize)) {
1250 DEBUG(0,("process_dgram: ignoring malformed2 (datasize = %d, len=%d, off=%d) datagram \
1251 packet sent to name %s from IP %s\n",
1252 dgram->datasize,
1253 len,
1254 (int)PTR_DIFF(buf2, dgram->data),
1255 nmb_namestr(&dgram->dest_name),
1256 inet_ntoa(p->ip) ));
1257 return;
1260 if ((buf2 + len < dgram->data) || (buf2 + len > dgram->data + dgram->datasize)) {
1261 DEBUG(0,("process_dgram: ignoring malformed3 (datasize = %d, len=%d, off=%d) datagram \
1262 packet sent to name %s from IP %s\n",
1263 dgram->datasize,
1264 len,
1265 (int)PTR_DIFF(buf2, dgram->data),
1266 nmb_namestr(&dgram->dest_name),
1267 inet_ntoa(p->ip) ));
1268 return;
1271 DEBUG(4,("process_dgram: datagram from %s to %s IP %s for %s of type %d len=%d\n",
1272 nmb_namestr(&dgram->source_name),nmb_namestr(&dgram->dest_name),
1273 inet_ntoa(p->ip), smb_buf(buf),CVAL(buf2,0),len));
1275 /* Datagram packet received for the browser mailslot */
1276 if (strequal(smb_buf(buf),BROWSE_MAILSLOT)) {
1277 process_browse_packet(p,buf2,len);
1278 return;
1281 /* Datagram packet received for the LAN Manager mailslot */
1282 if (strequal(smb_buf(buf),LANMAN_MAILSLOT)) {
1283 process_lanman_packet(p,buf2,len);
1284 return;
1287 /* Datagram packet received for the domain logon mailslot */
1288 if (strequal(smb_buf(buf),NET_LOGON_MAILSLOT)) {
1289 process_logon_packet(p,buf2,len,NET_LOGON_MAILSLOT);
1290 return;
1293 /* Datagram packet received for the NT domain logon mailslot */
1294 if (strequal(smb_buf(buf),NT_LOGON_MAILSLOT)) {
1295 process_logon_packet(p,buf2,len,NT_LOGON_MAILSLOT);
1296 return;
1299 unexpected_packet(p);
1302 /****************************************************************************
1303 Validate a response nmb packet.
1304 ****************************************************************************/
1306 static bool validate_nmb_response_packet( struct nmb_packet *nmb )
1308 bool ignore = False;
1310 switch (nmb->header.opcode) {
1311 case NMB_NAME_REG_OPCODE:
1312 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1313 case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1314 if (nmb->header.ancount == 0) {
1315 DEBUG(0,("validate_nmb_response_packet: Bad REG/REFRESH Packet. "));
1316 ignore = True;
1318 break;
1320 case NMB_NAME_QUERY_OPCODE:
1321 if ((nmb->header.ancount != 0) && (nmb->header.ancount != 1)) {
1322 DEBUG(0,("validate_nmb_response_packet: Bad QUERY Packet. "));
1323 ignore = True;
1325 break;
1327 case NMB_NAME_RELEASE_OPCODE:
1328 if (nmb->header.ancount == 0) {
1329 DEBUG(0,("validate_nmb_response_packet: Bad RELEASE Packet. "));
1330 ignore = True;
1332 break;
1334 case NMB_WACK_OPCODE:
1335 /* Check WACK response here. */
1336 if (nmb->header.ancount != 1) {
1337 DEBUG(0,("validate_nmb_response_packet: Bad WACK Packet. "));
1338 ignore = True;
1340 break;
1341 default:
1342 DEBUG(0,("validate_nmb_response_packet: Ignoring packet with unknown opcode %d.\n",
1343 nmb->header.opcode));
1344 return True;
1347 if(ignore)
1348 DEBUG(0,("Ignoring response packet with opcode %d.\n", nmb->header.opcode));
1350 return ignore;
1353 /****************************************************************************
1354 Validate a request nmb packet.
1355 ****************************************************************************/
1357 static bool validate_nmb_packet( struct nmb_packet *nmb )
1359 bool ignore = False;
1361 switch (nmb->header.opcode) {
1362 case NMB_NAME_REG_OPCODE:
1363 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1364 case NMB_NAME_REFRESH_OPCODE_9: /* WinNT uses 8 by default. */
1365 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1366 if (nmb->header.qdcount==0 || nmb->header.arcount==0) {
1367 DEBUG(0,("validate_nmb_packet: Bad REG/REFRESH Packet. "));
1368 ignore = True;
1370 break;
1372 case NMB_NAME_QUERY_OPCODE:
1373 if ((nmb->header.qdcount == 0) || ((nmb->question.question_type != QUESTION_TYPE_NB_QUERY) &&
1374 (nmb->question.question_type != QUESTION_TYPE_NB_STATUS))) {
1375 DEBUG(0,("validate_nmb_packet: Bad QUERY Packet. "));
1376 ignore = True;
1378 break;
1380 case NMB_NAME_RELEASE_OPCODE:
1381 if (nmb->header.qdcount==0 || nmb->header.arcount==0) {
1382 DEBUG(0,("validate_nmb_packet: Bad RELEASE Packet. "));
1383 ignore = True;
1385 break;
1386 default:
1387 DEBUG(0,("validate_nmb_packet: Ignoring packet with unknown opcode %d.\n",
1388 nmb->header.opcode));
1389 return True;
1392 if(ignore)
1393 DEBUG(0,("validate_nmb_packet: Ignoring request packet with opcode %d.\n", nmb->header.opcode));
1395 return ignore;
1398 /****************************************************************************
1399 Find a subnet (and potentially a response record) for a packet.
1400 ****************************************************************************/
1402 static struct subnet_record *find_subnet_for_nmb_packet( struct packet_struct *p,
1403 struct response_record **pprrec)
1405 struct nmb_packet *nmb = &p->packet.nmb;
1406 struct response_record *rrec = NULL;
1407 struct subnet_record *subrec = NULL;
1409 if(pprrec != NULL)
1410 *pprrec = NULL;
1412 if(nmb->header.response) {
1413 /* It's a response packet. Find a record for it or it's an error. */
1415 rrec = find_response_record( &subrec, nmb->header.name_trn_id);
1416 if(rrec == NULL) {
1417 DEBUG(3,("find_subnet_for_nmb_packet: response record not found for response id %hu\n",
1418 nmb->header.name_trn_id));
1419 unexpected_packet(p);
1420 return NULL;
1423 if(subrec == NULL) {
1424 DEBUG(0,("find_subnet_for_nmb_packet: subnet record not found for response id %hu\n",
1425 nmb->header.name_trn_id));
1426 return NULL;
1429 if(pprrec != NULL)
1430 *pprrec = rrec;
1431 return subrec;
1434 /* Try and see what subnet this packet belongs to. */
1436 /* WINS server ? */
1437 if(packet_is_for_wins_server(p))
1438 return wins_server_subnet;
1440 /* If it wasn't a broadcast packet then send to the UNICAST subnet. */
1441 if(nmb->header.nm_flags.bcast == False)
1442 return unicast_subnet;
1444 /* Go through all the broadcast subnets and see if the mask matches. */
1445 for (subrec = FIRST_SUBNET; subrec ; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1446 if(same_net_v4(p->ip, subrec->bcast_ip, subrec->mask_ip))
1447 return subrec;
1450 /* If none match it must have been a directed broadcast - assign the remote_broadcast_subnet. */
1451 return remote_broadcast_subnet;
1454 /****************************************************************************
1455 Process a nmb request packet - validate the packet and route it.
1456 ****************************************************************************/
1458 static void process_nmb_request(struct packet_struct *p)
1460 struct nmb_packet *nmb = &p->packet.nmb;
1461 struct subnet_record *subrec = NULL;
1463 debug_nmb_packet(p);
1465 /* Ensure we have a good packet. */
1466 if(validate_nmb_packet(nmb))
1467 return;
1469 /* Allocate a subnet to this packet - if we cannot - fail. */
1470 if((subrec = find_subnet_for_nmb_packet(p, NULL))==NULL)
1471 return;
1473 switch (nmb->header.opcode) {
1474 case NMB_NAME_REG_OPCODE:
1475 if(subrec == wins_server_subnet)
1476 wins_process_name_registration_request(subrec, p);
1477 else
1478 process_name_registration_request(subrec, p);
1479 break;
1481 case NMB_NAME_REFRESH_OPCODE_8: /* ambiguity in rfc1002 about which is correct. */
1482 case NMB_NAME_REFRESH_OPCODE_9:
1483 if(subrec == wins_server_subnet)
1484 wins_process_name_refresh_request(subrec, p);
1485 else
1486 process_name_refresh_request(subrec, p);
1487 break;
1489 case NMB_NAME_MULTIHOMED_REG_OPCODE:
1490 if(subrec == wins_server_subnet) {
1491 wins_process_multihomed_name_registration_request(subrec, p);
1492 } else {
1493 DEBUG(0,("process_nmb_request: Multihomed registration request must be \
1494 directed at a WINS server.\n"));
1496 break;
1498 case NMB_NAME_QUERY_OPCODE:
1499 switch (nmb->question.question_type) {
1500 case QUESTION_TYPE_NB_QUERY:
1501 if(subrec == wins_server_subnet)
1502 wins_process_name_query_request(subrec, p);
1503 else
1504 process_name_query_request(subrec, p);
1505 break;
1506 case QUESTION_TYPE_NB_STATUS:
1507 if(subrec == wins_server_subnet) {
1508 DEBUG(0,("process_nmb_request: NB_STATUS request directed at WINS server is \
1509 not allowed.\n"));
1510 break;
1511 } else {
1512 process_node_status_request(subrec, p);
1514 break;
1516 break;
1518 case NMB_NAME_RELEASE_OPCODE:
1519 if(subrec == wins_server_subnet)
1520 wins_process_name_release_request(subrec, p);
1521 else
1522 process_name_release_request(subrec, p);
1523 break;
1527 /****************************************************************************
1528 Process a nmb response packet - validate the packet and route it.
1529 to either the WINS server or a normal response.
1530 ****************************************************************************/
1532 static void process_nmb_response(struct packet_struct *p)
1534 struct nmb_packet *nmb = &p->packet.nmb;
1535 struct subnet_record *subrec = NULL;
1536 struct response_record *rrec = NULL;
1538 debug_nmb_packet(p);
1540 if(validate_nmb_response_packet(nmb))
1541 return;
1543 if((subrec = find_subnet_for_nmb_packet(p, &rrec))==NULL)
1544 return;
1546 if(rrec == NULL) {
1547 DEBUG(0,("process_nmb_response: response packet received but no response record \
1548 found for id = %hu. Ignoring packet.\n", nmb->header.name_trn_id));
1549 return;
1552 /* Increment the number of responses received for this record. */
1553 rrec->num_msgs++;
1554 /* Ensure we don't re-send the request. */
1555 rrec->repeat_count = 0;
1557 /* Call the response received function for this packet. */
1558 (*rrec->resp_fn)(subrec, rrec, p);
1561 /*******************************************************************
1562 Run elements off the packet queue till its empty
1563 ******************************************************************/
1565 void run_packet_queue(void)
1567 struct packet_struct *p;
1569 while ((p = packet_queue)) {
1570 DLIST_REMOVE(packet_queue, p);
1572 switch (p->packet_type) {
1573 case NMB_PACKET:
1574 if(p->packet.nmb.header.response)
1575 process_nmb_response(p);
1576 else
1577 process_nmb_request(p);
1578 break;
1580 case DGRAM_PACKET:
1581 process_dgram(p);
1582 break;
1584 free_packet(p);
1588 /*******************************************************************
1589 Retransmit or timeout elements from all the outgoing subnet response
1590 record queues. NOTE that this code must also check the WINS server
1591 subnet for response records to timeout as the WINS server code
1592 can send requests to check if a client still owns a name.
1593 (Patch from Andrey Alekseyev <fetch@muffin.arcadia.spb.ru>).
1594 ******************************************************************/
1596 void retransmit_or_expire_response_records(time_t t)
1598 struct subnet_record *subrec;
1600 for (subrec = FIRST_SUBNET; subrec; subrec = get_next_subnet_maybe_unicast_or_wins_server(subrec)) {
1601 struct response_record *rrec, *nextrrec;
1603 restart:
1605 for (rrec = subrec->responselist; rrec; rrec = nextrrec) {
1606 nextrrec = rrec->next;
1608 if (rrec->repeat_time <= t) {
1609 if (rrec->repeat_count > 0) {
1610 /* Resend while we have a non-zero repeat_count. */
1611 if(!send_packet(rrec->packet)) {
1612 DEBUG(0,("retransmit_or_expire_response_records: Failed to resend packet id %hu \
1613 to IP %s on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1615 rrec->repeat_time = t + rrec->repeat_interval;
1616 rrec->repeat_count--;
1617 } else {
1618 DEBUG(4,("retransmit_or_expire_response_records: timeout for packet id %hu to IP %s \
1619 on subnet %s\n", rrec->response_id, inet_ntoa(rrec->packet->ip), subrec->subnet_name));
1622 * Check the flag in this record to prevent recursion if we end
1623 * up in this function again via the timeout function call.
1626 if(!rrec->in_expiration_processing) {
1629 * Set the recursion protection flag in this record.
1632 rrec->in_expiration_processing = True;
1634 /* Call the timeout function. This will deal with removing the
1635 timed out packet. */
1636 if(rrec->timeout_fn) {
1637 (*rrec->timeout_fn)(subrec, rrec);
1638 } else {
1639 /* We must remove the record ourself if there is
1640 no timeout function. */
1641 remove_response_record(subrec, rrec);
1643 /* We have changed subrec->responselist,
1644 * restart from the beginning of this list. */
1645 goto restart;
1646 } /* !rrec->in_expitation_processing */
1647 } /* rrec->repeat_count > 0 */
1648 } /* rrec->repeat_time <= t */
1649 } /* end for rrec */
1650 } /* end for subnet */
1653 /****************************************************************************
1654 Create an fd_set containing all the sockets in the subnet structures,
1655 plus the broadcast sockets.
1656 ***************************************************************************/
1658 static bool create_listen_fdset(fd_set **ppset, int **psock_array, int *listen_number, int *maxfd)
1660 int *sock_array = NULL;
1661 struct subnet_record *subrec = NULL;
1662 int count = 0;
1663 int num = 0;
1664 fd_set *pset = SMB_MALLOC_P(fd_set);
1666 if(pset == NULL) {
1667 DEBUG(0,("create_listen_fdset: malloc fail !\n"));
1668 return True;
1671 /* The Client* sockets */
1672 count++;
1674 /* Check that we can add all the fd's we need. */
1675 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec))
1676 count++;
1678 /* each interface gets 4 sockets */
1679 count *= 4;
1681 if(count > FD_SETSIZE) {
1682 DEBUG(0,("create_listen_fdset: Too many file descriptors needed (%d). We can \
1683 only use %d.\n", count, FD_SETSIZE));
1684 SAFE_FREE(pset);
1685 return True;
1688 if((sock_array = SMB_MALLOC_ARRAY(int, count)) == NULL) {
1689 DEBUG(0,("create_listen_fdset: malloc fail for socket array. size %d\n", count));
1690 SAFE_FREE(pset);
1691 return True;
1694 FD_ZERO(pset);
1696 /* Add in the lp_socket_address() interface on 137. */
1697 FD_SET(ClientNMB,pset);
1698 sock_array[num++] = ClientNMB;
1699 *maxfd = MAX( *maxfd, ClientNMB);
1701 /* the lp_socket_address() interface has only one socket */
1702 sock_array[num++] = -1;
1704 /* Add in the 137 sockets on all the interfaces. */
1705 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1706 FD_SET(subrec->nmb_sock,pset);
1707 sock_array[num++] = subrec->nmb_sock;
1708 *maxfd = MAX( *maxfd, subrec->nmb_sock);
1710 sock_array[num++] = subrec->nmb_bcast;
1711 if (subrec->nmb_bcast != -1) {
1712 FD_SET(subrec->nmb_bcast,pset);
1713 *maxfd = MAX( *maxfd, subrec->nmb_bcast);
1717 /* Add in the lp_socket_address() interface on 138. */
1718 FD_SET(ClientDGRAM,pset);
1719 sock_array[num++] = ClientDGRAM;
1720 *maxfd = MAX( *maxfd, ClientDGRAM);
1722 /* the lp_socket_address() interface has only one socket */
1723 sock_array[num++] = -1;
1725 /* Add in the 138 sockets on all the interfaces. */
1726 for (subrec = FIRST_SUBNET; subrec; subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
1727 FD_SET(subrec->dgram_sock,pset);
1728 sock_array[num++] = subrec->dgram_sock;
1729 *maxfd = MAX( *maxfd, subrec->dgram_sock);
1731 sock_array[num++] = subrec->dgram_bcast;
1732 if (subrec->dgram_bcast != -1) {
1733 FD_SET(subrec->dgram_bcast,pset);
1734 *maxfd = MAX( *maxfd, subrec->dgram_bcast);
1738 *listen_number = count;
1740 SAFE_FREE(*ppset);
1741 SAFE_FREE(*psock_array);
1743 *ppset = pset;
1744 *psock_array = sock_array;
1746 return False;
1749 /****************************************************************************
1750 List of packets we're processing this select.
1751 ***************************************************************************/
1753 struct processed_packet {
1754 struct processed_packet *next;
1755 struct processed_packet *prev;
1756 enum packet_type packet_type;
1757 struct in_addr ip;
1758 int packet_id;
1761 /****************************************************************************
1762 Have we seen this before ?
1763 ***************************************************************************/
1765 static bool is_processed_packet(struct processed_packet *processed_packet_list,
1766 struct packet_struct *packet)
1768 struct processed_packet *p = NULL;
1770 for (p = processed_packet_list; p; p = p->next) {
1771 if (ip_equal_v4(p->ip, packet->ip) && p->packet_type == packet->packet_type) {
1772 if ((p->packet_type == NMB_PACKET) &&
1773 (p->packet_id ==
1774 packet->packet.nmb.header.name_trn_id)) {
1775 return true;
1776 } else if ((p->packet_type == DGRAM_PACKET) &&
1777 (p->packet_id ==
1778 packet->packet.dgram.header.dgm_id)) {
1779 return true;
1783 return false;
1786 /****************************************************************************
1787 Keep a list of what we've seen before.
1788 ***************************************************************************/
1790 static bool store_processed_packet(struct processed_packet **pp_processed_packet_list,
1791 struct packet_struct *packet)
1793 struct processed_packet *p = SMB_MALLOC_P(struct processed_packet);
1794 if (!p) {
1795 return false;
1797 p->packet_type = packet->packet_type;
1798 p->ip = packet->ip;
1799 if (packet->packet_type == NMB_PACKET) {
1800 p->packet_id = packet->packet.nmb.header.name_trn_id;
1801 } else if (packet->packet_type == DGRAM_PACKET) {
1802 p->packet_id = packet->packet.dgram.header.dgm_id;
1803 } else {
1804 return false;
1807 DLIST_ADD(*pp_processed_packet_list, p);
1808 return true;
1811 /****************************************************************************
1812 Throw away what we've seen before.
1813 ***************************************************************************/
1815 static void free_processed_packet_list(struct processed_packet **pp_processed_packet_list)
1817 struct processed_packet *p = NULL, *next = NULL;
1819 for (p = *pp_processed_packet_list; p; p = next) {
1820 next = p->next;
1821 DLIST_REMOVE(*pp_processed_packet_list, p);
1822 SAFE_FREE(p);
1826 /****************************************************************************
1827 Listens for NMB or DGRAM packets, and queues them.
1828 return True if the socket is dead
1829 ***************************************************************************/
1831 bool listen_for_packets(bool run_election)
1833 static fd_set *listen_set = NULL;
1834 static int listen_number = 0;
1835 static int *sock_array = NULL;
1836 int i;
1837 static int maxfd = 0;
1839 fd_set r_fds;
1840 fd_set w_fds;
1841 int selrtn;
1842 struct timeval timeout;
1843 #ifndef SYNC_DNS
1844 int dns_fd;
1845 #endif
1846 struct processed_packet *processed_packet_list = NULL;
1848 if(listen_set == NULL || rescan_listen_set) {
1849 if(create_listen_fdset(&listen_set, &sock_array, &listen_number, &maxfd)) {
1850 DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
1851 return True;
1853 rescan_listen_set = False;
1856 memcpy((char *)&r_fds, (char *)listen_set, sizeof(fd_set));
1857 FD_ZERO(&w_fds);
1859 #ifndef SYNC_DNS
1860 dns_fd = asyncdns_fd();
1861 if (dns_fd != -1) {
1862 FD_SET(dns_fd, &r_fds);
1863 maxfd = MAX( maxfd, dns_fd);
1865 #endif
1867 /* Process a signal and timer events now... */
1868 if (run_events(nmbd_event_context(), 0, NULL, NULL)) {
1869 return False;
1873 * During elections and when expecting a netbios response packet we
1874 * need to send election packets at tighter intervals.
1875 * Ideally it needs to be the interval (in ms) between time now and
1876 * the time we are expecting the next netbios packet.
1879 timeout.tv_sec = (run_election||num_response_packets) ? 1 : NMBD_SELECT_LOOP;
1880 timeout.tv_usec = 0;
1883 struct timeval now = timeval_current();
1884 event_add_to_select_args(nmbd_event_context(), &now,
1885 &r_fds, &w_fds, &timeout, &maxfd);
1888 selrtn = sys_select(maxfd+1,&r_fds,&w_fds,NULL,&timeout);
1890 if (run_events(nmbd_event_context(), selrtn, &r_fds, &w_fds)) {
1891 return False;
1894 if (selrtn == -1) {
1895 return False;
1898 #ifndef SYNC_DNS
1899 if (dns_fd != -1 && FD_ISSET(dns_fd,&r_fds)) {
1900 run_dns_queue();
1902 #endif
1904 for(i = 0; i < listen_number; i++) {
1905 enum packet_type packet_type;
1906 struct packet_struct *packet;
1907 const char *packet_name;
1908 int client_fd;
1909 int client_port;
1911 if (sock_array[i] == -1) {
1912 continue;
1915 if (!FD_ISSET(sock_array[i],&r_fds)) {
1916 continue;
1919 if (i < (listen_number/2)) {
1920 /* Port 137 */
1921 packet_type = NMB_PACKET;
1922 packet_name = "nmb";
1923 client_fd = ClientNMB;
1924 client_port = global_nmb_port;
1925 } else {
1926 /* Port 138 */
1927 packet_type = DGRAM_PACKET;
1928 packet_name = "dgram";
1929 client_fd = ClientDGRAM;
1930 client_port = DGRAM_PORT;
1933 packet = read_packet(sock_array[i], packet_type);
1934 if (!packet) {
1935 continue;
1939 * If we got a packet on the broadcast socket and interfaces
1940 * only is set then check it came from one of our local nets.
1942 if (lp_bind_interfaces_only() &&
1943 (sock_array[i] == client_fd) &&
1944 (!is_local_net_v4(packet->ip))) {
1945 DEBUG(7,("discarding %s packet sent to broadcast socket from %s:%d\n",
1946 packet_name, inet_ntoa(packet->ip), packet->port));
1947 free_packet(packet);
1948 continue;
1951 if ((is_loopback_ip_v4(packet->ip) || ismyip_v4(packet->ip)) &&
1952 packet->port == client_port)
1954 if (client_port == DGRAM_PORT) {
1955 DEBUG(7,("discarding own dgram packet from %s:%d\n",
1956 inet_ntoa(packet->ip),packet->port));
1957 free_packet(packet);
1958 continue;
1961 if (packet->packet.nmb.header.nm_flags.bcast) {
1962 DEBUG(7,("discarding own nmb bcast packet from %s:%d\n",
1963 inet_ntoa(packet->ip),packet->port));
1964 free_packet(packet);
1965 continue;
1970 if (is_processed_packet(processed_packet_list, packet)) {
1971 DEBUG(7,("discarding duplicate packet from %s:%d\n",
1972 inet_ntoa(packet->ip),packet->port));
1973 free_packet(packet);
1974 continue;
1977 store_processed_packet(&processed_packet_list, packet);
1980 * 0,2,4,... are unicast sockets
1981 * 1,3,5,... are broadcast sockets
1983 * on broadcast socket we only receive packets
1984 * and send replies via the unicast socket.
1986 * 0,1 and 2,3 and ... belong together.
1988 if ((i % 2) != 0) {
1989 /* this is a broadcast socket */
1990 packet->send_fd = sock_array[i-1];
1991 } else {
1992 /* this is already a unicast socket */
1993 packet->send_fd = sock_array[i];
1996 queue_packet(packet);
1999 free_processed_packet_list(&processed_packet_list);
2000 return False;
2003 /****************************************************************************
2004 Construct and send a netbios DGRAM.
2005 **************************************************************************/
2007 bool send_mailslot(bool unique, const char *mailslot,char *buf, size_t len,
2008 const char *srcname, int src_type,
2009 const char *dstname, int dest_type,
2010 struct in_addr dest_ip,struct in_addr src_ip,
2011 int dest_port)
2013 bool loopback_this_packet = False;
2014 struct packet_struct p;
2015 struct dgram_packet *dgram = &p.packet.dgram;
2016 char *ptr,*p2;
2017 char tmp[4];
2019 memset((char *)&p,'\0',sizeof(p));
2021 if(ismyip_v4(dest_ip) && (dest_port == DGRAM_PORT)) /* Only if to DGRAM_PORT */
2022 loopback_this_packet = True;
2024 /* generate_name_trn_id(); */ /* Not used, so gone, RJS */
2026 /* DIRECT GROUP or UNIQUE datagram. */
2027 dgram->header.msg_type = unique ? 0x10 : 0x11;
2028 dgram->header.flags.node_type = M_NODE;
2029 dgram->header.flags.first = True;
2030 dgram->header.flags.more = False;
2031 dgram->header.dgm_id = generate_name_trn_id();
2032 dgram->header.source_ip = src_ip;
2033 dgram->header.source_port = DGRAM_PORT;
2034 dgram->header.dgm_length = 0; /* Let build_dgram() handle this. */
2035 dgram->header.packet_offset = 0;
2037 make_nmb_name(&dgram->source_name,srcname,src_type);
2038 make_nmb_name(&dgram->dest_name,dstname,dest_type);
2040 ptr = &dgram->data[0];
2042 /* Setup the smb part. */
2043 ptr -= 4; /* XXX Ugliness because of handling of tcp SMB length. */
2044 memcpy(tmp,ptr,4);
2046 if (smb_size + 17*2 + strlen(mailslot) + 1 + len > MAX_DGRAM_SIZE) {
2047 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
2048 return false;
2051 cli_set_message(ptr,17,strlen(mailslot) + 1 + len,True);
2052 memcpy(ptr,tmp,4);
2054 SCVAL(ptr,smb_com,SMBtrans);
2055 SSVAL(ptr,smb_vwv1,len);
2056 SSVAL(ptr,smb_vwv11,len);
2057 SSVAL(ptr,smb_vwv12,70 + strlen(mailslot));
2058 SSVAL(ptr,smb_vwv13,3);
2059 SSVAL(ptr,smb_vwv14,1);
2060 SSVAL(ptr,smb_vwv15,1);
2061 SSVAL(ptr,smb_vwv16,2);
2062 p2 = smb_buf(ptr);
2063 safe_strcpy_base(p2, mailslot, dgram->data, sizeof(dgram->data));
2064 p2 = skip_string(ptr,MAX_DGRAM_SIZE,p2);
2066 if (((p2+len) > dgram->data+sizeof(dgram->data)) || ((p2+len) < p2)) {
2067 DEBUG(0, ("send_mailslot: Cannot write beyond end of packet\n"));
2068 return False;
2069 } else {
2070 if (len) {
2071 memcpy(p2,buf,len);
2073 p2 += len;
2076 dgram->datasize = PTR_DIFF(p2,ptr+4); /* +4 for tcp length. */
2078 p.ip = dest_ip;
2079 p.port = dest_port;
2080 p.recv_fd = -1;
2081 p.send_fd = find_subnet_mailslot_fd_for_address( src_ip );
2082 p.timestamp = time(NULL);
2083 p.packet_type = DGRAM_PACKET;
2085 DEBUG(4,("send_mailslot: Sending to mailslot %s from %s IP %s ", mailslot,
2086 nmb_namestr(&dgram->source_name), inet_ntoa(src_ip)));
2087 DEBUG(4,("to %s IP %s\n", nmb_namestr(&dgram->dest_name), inet_ntoa(dest_ip)));
2089 debug_browse_data(buf, len);
2091 if(loopback_this_packet) {
2092 struct packet_struct *lo_packet = NULL;
2093 DEBUG(5,("send_mailslot: sending packet to ourselves.\n"));
2094 if((lo_packet = copy_packet(&p)) == NULL)
2095 return False;
2096 queue_packet(lo_packet);
2097 return True;
2098 } else {
2099 return(send_packet(&p));