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