xref: /haiku/src/add-ons/kernel/network/datalink_protocols/arp/arp.cpp (revision 1345706a9ff6ad0dc041339a02d4259998b0765d)
1 /*
2  * Copyright 2006-2010, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Axel Dörfler, axeld@pinc-software.de
7  *		Hugo Santos, hugosantos@gmail.com
8  */
9 
10 
11 //! Ethernet Address Resolution Protocol, see RFC 826.
12 
13 
14 #include <arp_control.h>
15 #include <net_datalink_protocol.h>
16 #include <net_device.h>
17 #include <net_datalink.h>
18 #include <net_stack.h>
19 #include <NetBufferUtilities.h>
20 
21 #include <generic_syscall.h>
22 #include <util/atomic.h>
23 #include <util/AutoLock.h>
24 #include <util/DoublyLinkedList.h>
25 #include <util/khash.h>
26 
27 #include <ByteOrder.h>
28 #include <KernelExport.h>
29 
30 #include <net/if.h>
31 #include <net/if_dl.h>
32 #include <net/if_types.h>
33 #include <new>
34 #include <stdio.h>
35 #include <string.h>
36 #include <sys/sockio.h>
37 
38 
39 //#define TRACE_ARP
40 #ifdef TRACE_ARP
41 #	define TRACE(x) dprintf x
42 #else
43 #	define TRACE(x) ;
44 #endif
45 
46 
47 struct arp_header {
48 	uint16		hardware_type;
49 	uint16		protocol_type;
50 	uint8		hardware_length;
51 	uint8		protocol_length;
52 	uint16		opcode;
53 
54 	// TODO: this should be a variable length header, but for our current
55 	//	usage (Ethernet/IPv4), this should work fine.
56 	uint8		hardware_sender[6];
57 	in_addr_t	protocol_sender;
58 	uint8		hardware_target[6];
59 	in_addr_t	protocol_target;
60 } _PACKED;
61 
62 #define ARP_OPCODE_REQUEST	1
63 #define ARP_OPCODE_REPLY	2
64 
65 #define ARP_HARDWARE_TYPE_ETHER	1
66 
67 struct arp_entry {
68 	arp_entry	*next;
69 	in_addr_t	protocol_address;
70 	sockaddr_dl	hardware_address;
71 	uint32		flags;
72 	net_buffer	*request_buffer;
73 	net_timer	timer;
74 	uint32		timer_state;
75 	bigtime_t	timestamp;
76 	net_datalink_protocol *protocol;
77 
78 	typedef DoublyLinkedListCLink<net_buffer> NetBufferLink;
79 	typedef DoublyLinkedList<net_buffer, NetBufferLink> BufferList;
80 
81 	BufferList  queue;
82 
83 	static int Compare(void *_entry, const void *_key);
84 	static uint32 Hash(void *_entry, const void *_key, uint32 range);
85 	static arp_entry *Lookup(in_addr_t protocolAddress);
86 	static arp_entry *Add(in_addr_t protocolAddress,
87 		sockaddr_dl *hardwareAddress, uint32 flags);
88 
89 	~arp_entry();
90 
91 	void ClearQueue();
92 	void MarkFailed();
93 	void MarkValid();
94 	void ScheduleRemoval();
95 };
96 
97 // see arp_control.h for more flags
98 #define ARP_FLAG_REMOVED			0x00010000
99 #define ARP_PUBLIC_FLAG_MASK		0x0000ffff
100 
101 #define ARP_NO_STATE				0
102 #define ARP_STATE_REQUEST			1
103 #define ARP_STATE_LAST_REQUEST		5
104 #define ARP_STATE_REQUEST_FAILED	6
105 #define ARP_STATE_REMOVE_FAILED		7
106 #define ARP_STATE_STALE				8
107 
108 #define ARP_STALE_TIMEOUT	30 * 60000000LL		// 30 minutes
109 #define ARP_REJECT_TIMEOUT	20000000LL			// 20 seconds
110 #define ARP_REQUEST_TIMEOUT	1000000LL			// 1 second
111 
112 struct arp_protocol : net_datalink_protocol {
113 	sockaddr_dl	hardware_address;
114 	in_addr_t	local_address;
115 };
116 
117 
118 static const net_buffer* kDeletedBuffer = (net_buffer*)~0;
119 
120 static void arp_timer(struct net_timer *timer, void *data);
121 
122 net_buffer_module_info* gBufferModule;
123 static net_stack_module_info* sStackModule;
124 static net_datalink_module_info* sDatalinkModule;
125 static hash_table* sCache;
126 static mutex sCacheLock;
127 static bool sIgnoreReplies;
128 
129 
130 #ifdef TRACE_ARP
131 
132 
133 const char*
134 mac_to_string(uint8* address)
135 {
136 	static char buffer[20];
137 	snprintf(buffer, sizeof(buffer), "%02x:%02x:%02x:%02x:%02x:%02x",
138 		address[0], address[1], address[2], address[3], address[4], address[5]);
139 	return buffer;
140 }
141 
142 
143 const char*
144 inet_to_string(in_addr_t address)
145 {
146 	static char buffer[20];
147 
148 	unsigned int hostAddress = ntohl(address);
149 	snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d",
150 		hostAddress >> 24, (hostAddress >> 16) & 0xff,
151 		(hostAddress >> 8) & 0xff, hostAddress & 0xff);
152 	return buffer;
153 }
154 
155 
156 #endif	// TRACE_ARP
157 
158 
159 static net_buffer*
160 get_request_buffer(arp_entry* entry)
161 {
162 	net_buffer* buffer = entry->request_buffer;
163 	if (buffer == NULL || buffer == kDeletedBuffer)
164 		return NULL;
165 
166 	buffer = atomic_pointer_test_and_set(&entry->request_buffer,
167 		(net_buffer*)NULL, buffer);
168 	if (buffer == kDeletedBuffer)
169 		return NULL;
170 
171 	return buffer;
172 }
173 
174 
175 static void
176 put_request_buffer(arp_entry* entry, net_buffer* buffer)
177 {
178 	net_buffer* requestBuffer = atomic_pointer_test_and_set(
179 		&entry->request_buffer, buffer, (net_buffer*)NULL);
180 	if (requestBuffer != NULL) {
181 		// someone else took over ownership of the request buffer
182 		gBufferModule->free(buffer);
183 	}
184 }
185 
186 
187 static void
188 delete_request_buffer(arp_entry* entry)
189 {
190 	net_buffer* buffer = atomic_pointer_set(&entry->request_buffer,
191 		kDeletedBuffer);
192 	if (buffer != NULL && buffer != kDeletedBuffer)
193 		gBufferModule->free(buffer);
194 }
195 
196 
197 static void
198 ipv4_to_ether_multicast(sockaddr_dl *destination, const sockaddr_in *source)
199 {
200 	// RFC 1112 - Host extensions for IP multicasting
201 	//
202 	//   ``An IP host group address is mapped to an Ethernet multicast
203 	//   address by placing the low-order 23-bits of the IP address into
204 	//   the low-order 23 bits of the Ethernet multicast address
205 	//   01-00-5E-00-00-00 (hex).''
206 
207 	destination->sdl_len = sizeof(sockaddr_dl);
208 	destination->sdl_family = AF_LINK;
209 	destination->sdl_index = 0;
210 	destination->sdl_type = IFT_ETHER;
211 	destination->sdl_e_type = ETHER_TYPE_IP;
212 	destination->sdl_nlen = destination->sdl_slen = 0;
213 	destination->sdl_alen = ETHER_ADDRESS_LENGTH;
214 
215 	memcpy(LLADDR(destination) + 2, &source->sin_addr, sizeof(in_addr));
216 	uint32 *data = (uint32 *)LLADDR(destination);
217 	data[0] = (data[0] & htonl(0x7f)) | htonl(0x01005e00);
218 }
219 
220 
221 // #pragma mark -
222 
223 
224 /*static*/ int
225 arp_entry::Compare(void *_entry, const void *_key)
226 {
227 	arp_entry *entry = (arp_entry *)_entry;
228 	in_addr_t *key = (in_addr_t *)_key;
229 
230 	if (entry->protocol_address == *key)
231 		return 0;
232 
233 	return 1;
234 }
235 
236 
237 /*static*/ uint32
238 arp_entry::Hash(void *_entry, const void *_key, uint32 range)
239 {
240 	arp_entry *entry = (arp_entry *)_entry;
241 	const in_addr_t *key = (const in_addr_t *)_key;
242 
243 // TODO: check if this makes a good hash...
244 #define HASH(o) ((((o) >> 24) ^ ((o) >> 16) ^ ((o) >> 8) ^ (o)) % range)
245 
246 #if 0
247 	in_addr_t a = entry ? entry->protocol_address : *key;
248 	dprintf("%ld.%ld.%ld.%ld: Hash: %lu\n", a >> 24, (a >> 16) & 0xff,
249 		(a >> 8) & 0xff, a & 0xff, HASH(a));
250 #endif
251 
252 	if (entry != NULL)
253 		return HASH(entry->protocol_address);
254 
255 	return HASH(*key);
256 #undef HASH
257 }
258 
259 
260 /*static*/ arp_entry *
261 arp_entry::Lookup(in_addr_t address)
262 {
263 	return (arp_entry *)hash_lookup(sCache, &address);
264 }
265 
266 
267 /*static*/ arp_entry *
268 arp_entry::Add(in_addr_t protocolAddress, sockaddr_dl *hardwareAddress,
269 	uint32 flags)
270 {
271 	ASSERT_LOCKED_MUTEX(&sCacheLock);
272 
273 	arp_entry *entry = new (std::nothrow) arp_entry;
274 	if (entry == NULL)
275 		return NULL;
276 
277 	entry->protocol_address = protocolAddress;
278 	entry->flags = flags;
279 	entry->timestamp = system_time();
280 	entry->protocol = NULL;
281 	entry->request_buffer = NULL;
282 	entry->timer_state = ARP_NO_STATE;
283 	sStackModule->init_timer(&entry->timer, arp_timer, entry);
284 
285 	if (hardwareAddress != NULL) {
286 		// this entry is already resolved
287 		entry->hardware_address = *hardwareAddress;
288 		entry->hardware_address.sdl_e_type = ETHER_TYPE_IP;
289 	} else {
290 		// this entry still needs to be resolved
291 		entry->hardware_address.sdl_alen = 0;
292 	}
293 	if (entry->hardware_address.sdl_len != sizeof(sockaddr_dl)) {
294 		// explicitly set correct length in case our caller hasn't...
295 		entry->hardware_address.sdl_len = sizeof(sockaddr_dl);
296 	}
297 
298 	if (hash_insert(sCache, entry) != B_OK) {
299 		// We can delete the entry here with the sCacheLock held, since it's
300 		// guaranteed there are no timers pending.
301 		delete entry;
302 		return NULL;
303 	}
304 
305 	return entry;
306 }
307 
308 
309 arp_entry::~arp_entry()
310 {
311 	// make sure there is no active timer left for us
312 	sStackModule->cancel_timer(&timer);
313 	sStackModule->wait_for_timer(&timer);
314 
315 	ClearQueue();
316 }
317 
318 
319 void
320 arp_entry::ClearQueue()
321 {
322 	BufferList::Iterator iterator = queue.GetIterator();
323 	while (iterator.HasNext()) {
324 		net_buffer *buffer = iterator.Next();
325 		iterator.Remove();
326 		gBufferModule->free(buffer);
327 	}
328 }
329 
330 
331 void
332 arp_entry::MarkFailed()
333 {
334 	TRACE(("ARP entry %p Marked as FAILED\n", this));
335 
336 	flags = (flags & ~ARP_FLAG_VALID) | ARP_FLAG_REJECT;
337 	ClearQueue();
338 }
339 
340 
341 void
342 arp_entry::MarkValid()
343 {
344 	TRACE(("ARP entry %p Marked as VALID, have %li packets queued.\n", this,
345 		queue.Count()));
346 
347 	flags = (flags & ~ARP_FLAG_REJECT) | ARP_FLAG_VALID;
348 
349 	BufferList::Iterator iterator = queue.GetIterator();
350 	while (iterator.HasNext()) {
351 		net_buffer *buffer = iterator.Next();
352 		iterator.Remove();
353 
354 		TRACE(("  ARP Dequeing packet %p...\n", buffer));
355 
356 		memcpy(buffer->destination, &hardware_address,
357 			hardware_address.sdl_len);
358 		protocol->next->module->send_data(protocol->next, buffer);
359 	}
360 }
361 
362 
363 void
364 arp_entry::ScheduleRemoval()
365 {
366 	// schedule a timer to remove this entry
367 	timer_state = ARP_STATE_REMOVE_FAILED;
368 	sStackModule->set_timer(&timer, 0);
369 }
370 
371 
372 //	#pragma mark -
373 
374 
375 /*!	Updates the entry determined by \a protocolAddress with the specified
376 	\a hardwareAddress.
377 	If such an entry does not exist yet, a new entry is added. If you try
378 	to update a local existing entry but didn't ask for it (by setting
379 	\a flags to ARP_FLAG_LOCAL), an error is returned.
380 
381 	This function does not lock the cache - you have to do it yourself
382 	before calling it.
383 */
384 static status_t
385 arp_update_entry(in_addr_t protocolAddress, sockaddr_dl *hardwareAddress,
386 	uint32 flags, arp_entry **_entry = NULL)
387 {
388 	ASSERT_LOCKED_MUTEX(&sCacheLock);
389 	TRACE(("%s(%s, %s, flags 0x%" B_PRIx32 ")\n", __FUNCTION__,
390 		inet_to_string(protocolAddress), mac_to_string(LLADDR(hardwareAddress)),
391 		flags));
392 
393 	arp_entry *entry = arp_entry::Lookup(protocolAddress);
394 	if (entry != NULL) {
395 		// We disallow updating of entries that had been resolved before,
396 		// but to a different address (only for those that belong to a
397 		// specific address - redefining INADDR_ANY is always allowed).
398 		// Right now, you have to manually purge the ARP entries (or wait some
399 		// time) to let us switch to the new address.
400 		if (protocolAddress != INADDR_ANY
401 			&& entry->hardware_address.sdl_alen != 0
402 			&& memcmp(LLADDR(&entry->hardware_address),
403 				LLADDR(hardwareAddress), ETHER_ADDRESS_LENGTH)) {
404 			uint8* data = LLADDR(hardwareAddress);
405 			dprintf("ARP host %08x updated with different hardware address "
406 				"%02x:%02x:%02x:%02x:%02x:%02x.\n", protocolAddress,
407 				data[0], data[1], data[2], data[3], data[4], data[5]);
408 			return B_ERROR;
409 		}
410 
411 		entry->hardware_address = *hardwareAddress;
412 		entry->timestamp = system_time();
413 	} else {
414 		entry = arp_entry::Add(protocolAddress, hardwareAddress, flags);
415 		if (entry == NULL)
416 			return B_NO_MEMORY;
417 	}
418 
419 	delete_request_buffer(entry);
420 
421 	if ((entry->flags & ARP_FLAG_PERMANENT) == 0) {
422 		// (re)start the stale timer
423 		entry->timer_state = ARP_STATE_STALE;
424 		sStackModule->set_timer(&entry->timer, ARP_STALE_TIMEOUT);
425 	}
426 
427 	if ((entry->flags & ARP_FLAG_REJECT) != 0)
428 		entry->MarkFailed();
429 	else
430 		entry->MarkValid();
431 
432 	if (_entry)
433 		*_entry = entry;
434 
435 	return B_OK;
436 }
437 
438 
439 static void
440 arp_remove_local_entry(arp_protocol* protocol, const sockaddr* local,
441 	bool updateLocalAddress)
442 {
443 	in_addr_t inetAddress;
444 
445 	if (local == NULL) {
446 		// interface has not yet been set
447 		inetAddress = INADDR_ANY;
448 	} else
449 		inetAddress = ((sockaddr_in*)local)->sin_addr.s_addr;
450 
451 	TRACE(("%s(): address %s\n", __FUNCTION__, inet_to_string(inetAddress)));
452 
453 	MutexLocker locker(sCacheLock);
454 
455 	arp_entry* entry = arp_entry::Lookup(inetAddress);
456 	if (entry != NULL) {
457 		hash_remove(sCache, entry);
458 		entry->flags |= ARP_FLAG_REMOVED;
459 	}
460 
461 	if (updateLocalAddress && protocol->local_address == inetAddress) {
462 		// find new local sender address
463 		protocol->local_address = 0;
464 
465 		net_interface_address* address = NULL;
466 		while (sDatalinkModule->get_next_interface_address(protocol->interface,
467 				&address)) {
468 			if (address->local == NULL || address->local->sa_family != AF_INET)
469 				continue;
470 
471 			protocol->local_address
472 				= ((sockaddr_in*)address->local)->sin_addr.s_addr;
473 		}
474 	}
475 
476 	locker.Unlock();
477 	delete entry;
478 }
479 
480 
481 /*!	Removes all entries belonging to the local interface of the \a procotol
482 	given.
483 */
484 static void
485 arp_remove_local(arp_protocol* protocol)
486 {
487 	net_interface_address* address = NULL;
488 	while (sDatalinkModule->get_next_interface_address(protocol->interface,
489 			&address)) {
490 		if (address->local == NULL || address->local->sa_family != AF_INET)
491 			continue;
492 
493 		arp_remove_local_entry(protocol, address->local, false);
494 	}
495 }
496 
497 
498 static status_t
499 arp_set_local_entry(arp_protocol* protocol, const sockaddr* local)
500 {
501 	MutexLocker locker(sCacheLock);
502 
503 	net_interface* interface = protocol->interface;
504 	in_addr_t inetAddress;
505 
506 	if (local == NULL) {
507 		// interface has not yet been set
508 		inetAddress = INADDR_ANY;
509 	} else
510 		inetAddress = ((sockaddr_in*)local)->sin_addr.s_addr;
511 
512 	TRACE(("%s(): address %s\n", __FUNCTION__, inet_to_string(inetAddress)));
513 
514 	if (protocol->local_address == 0)
515 		protocol->local_address = inetAddress;
516 
517 	sockaddr_dl address;
518 	address.sdl_len = sizeof(sockaddr_dl);
519 	address.sdl_family = AF_LINK;
520 	address.sdl_type = IFT_ETHER;
521 	address.sdl_e_type = ETHER_TYPE_IP;
522 	address.sdl_nlen = 0;
523 	address.sdl_slen = 0;
524 	address.sdl_alen = interface->device->address.length;
525 	memcpy(LLADDR(&address), interface->device->address.data, address.sdl_alen);
526 
527 	memcpy(&protocol->hardware_address, &address, sizeof(sockaddr_dl));
528 		// cache the address in our protocol
529 
530 	arp_entry* entry;
531 	status_t status = arp_update_entry(inetAddress, &address,
532 		ARP_FLAG_LOCAL | ARP_FLAG_PERMANENT, &entry);
533 	if (status == B_OK)
534 		entry->protocol = protocol;
535 
536 	return status;
537 }
538 
539 
540 /*!	Creates permanent local entries for all addresses of the interface belonging
541 	to this protocol.
542 	Returns an error if no entry could be added.
543 */
544 static status_t
545 arp_update_local(arp_protocol* protocol)
546 {
547 	protocol->local_address = 0;
548 		// TODO: test if this actually works - maybe we should use
549 		// INADDR_BROADCAST instead
550 
551 	ssize_t count = 0;
552 
553 	net_interface_address* address = NULL;
554 	while (sDatalinkModule->get_next_interface_address(protocol->interface,
555 			&address)) {
556 		if (address->local == NULL || address->local->sa_family != AF_INET)
557 			continue;
558 
559 		if (arp_set_local_entry(protocol, address->local) == B_OK) {
560 			count++;
561 		}
562 	}
563 
564 	if (count == 0)
565 		return arp_set_local_entry(protocol, NULL);
566 
567 	return B_OK;
568 }
569 
570 
571 static status_t
572 handle_arp_request(net_buffer *buffer, arp_header &header)
573 {
574 	MutexLocker locker(sCacheLock);
575 
576 	if (!sIgnoreReplies) {
577 		arp_update_entry(header.protocol_sender,
578 			(sockaddr_dl *)buffer->source, 0);
579 			// remember the address of the sender as we might need it later
580 	}
581 
582 	// check if this request is for us
583 
584 	arp_entry *entry = arp_entry::Lookup(header.protocol_target);
585 	if (entry == NULL || entry->protocol == NULL
586 		|| (entry->flags & (ARP_FLAG_LOCAL | ARP_FLAG_PUBLISH)) == 0) {
587 		// We're not the one to answer this request
588 		// TODO: instead of letting the other's request time-out, can we reply
589 		//	failure somehow?
590 		TRACE(("  not for us\n"));
591 		return B_ERROR;
592 	}
593 
594 	// send a reply (by reusing the buffer we got)
595 
596 	TRACE(("  send reply!\n"));
597 	header.opcode = htons(ARP_OPCODE_REPLY);
598 
599 	memcpy(header.hardware_target, header.hardware_sender, ETHER_ADDRESS_LENGTH);
600 	header.protocol_target = header.protocol_sender;
601 	memcpy(header.hardware_sender, LLADDR(&entry->hardware_address),
602 		ETHER_ADDRESS_LENGTH);
603 	header.protocol_sender = entry->protocol_address;
604 
605 	// exchange source and destination address
606 	memcpy(LLADDR((sockaddr_dl *)buffer->source), header.hardware_sender,
607 		ETHER_ADDRESS_LENGTH);
608 	memcpy(LLADDR((sockaddr_dl *)buffer->destination), header.hardware_target,
609 		ETHER_ADDRESS_LENGTH);
610 
611 	buffer->flags = 0;
612 		// make sure this won't be a broadcast message
613 
614 	return entry->protocol->next->module->send_data(entry->protocol->next,
615 		buffer);
616 }
617 
618 
619 static void
620 handle_arp_reply(net_buffer *buffer, arp_header &header)
621 {
622 	if (sIgnoreReplies)
623 		return;
624 
625 	MutexLocker locker(sCacheLock);
626 	arp_update_entry(header.protocol_sender, (sockaddr_dl *)buffer->source, 0);
627 }
628 
629 
630 static status_t
631 arp_receive(void *cookie, net_device *device, net_buffer *buffer)
632 {
633 	TRACE(("ARP receive\n"));
634 
635 	NetBufferHeaderReader<arp_header> bufferHeader(buffer);
636 	if (bufferHeader.Status() < B_OK)
637 		return bufferHeader.Status();
638 
639 	arp_header &header = bufferHeader.Data();
640 	uint16 opcode = ntohs(header.opcode);
641 
642 #ifdef TRACE_ARP
643 	dprintf("  hw sender: %s\n", mac_to_string(header.hardware_sender));
644 	dprintf("  proto sender: %s\n", inet_to_string(header.protocol_sender));
645 	dprintf("  hw target: %s\n", mac_to_string(header.hardware_target));;
646 	dprintf("  proto target: %s\n", inet_to_string(header.protocol_target));
647 #endif	// TRACE_ARP
648 
649 	if (ntohs(header.protocol_type) != ETHER_TYPE_IP
650 		|| ntohs(header.hardware_type) != ARP_HARDWARE_TYPE_ETHER)
651 		return B_BAD_TYPE;
652 
653 	// check if the packet is okay
654 
655 	if (header.hardware_length != ETHER_ADDRESS_LENGTH
656 		|| header.protocol_length != sizeof(in_addr_t))
657 		return B_BAD_DATA;
658 
659 	// handle packet
660 
661 	switch (opcode) {
662 		case ARP_OPCODE_REQUEST:
663 			TRACE(("  got ARP request\n"));
664 			if (handle_arp_request(buffer, header) == B_OK) {
665 				// the function will take care of the buffer if everything
666 				// went well
667 				return B_OK;
668 			}
669 			break;
670 		case ARP_OPCODE_REPLY:
671 			TRACE(("  got ARP reply\n"));
672 			handle_arp_reply(buffer, header);
673 			break;
674 
675 		default:
676 			dprintf("unknown ARP opcode %d\n", opcode);
677 			return B_ERROR;
678 	}
679 
680 	gBufferModule->free(buffer);
681 	return B_OK;
682 }
683 
684 
685 static void
686 arp_timer(struct net_timer *timer, void *data)
687 {
688 	arp_entry *entry = (arp_entry *)data;
689 	TRACE(("ARP timer %ld, entry %p!\n", entry->timer_state, entry));
690 
691 	switch (entry->timer_state) {
692 		case ARP_NO_STATE:
693 			// who are you kidding?
694 			break;
695 
696 		case ARP_STATE_REQUEST_FAILED:
697 			// Requesting the ARP entry failed, we keep it around for a while,
698 			// though, so that we won't try to request the same address again
699 			// too soon.
700 			TRACE(("  requesting ARP entry %p failed!\n", entry));
701 			entry->timer_state = ARP_STATE_REMOVE_FAILED;
702 			entry->MarkFailed();
703 			sStackModule->set_timer(&entry->timer, ARP_REJECT_TIMEOUT);
704 			break;
705 
706 		case ARP_STATE_REMOVE_FAILED:
707 		case ARP_STATE_STALE:
708 		{
709 			// the entry has aged so much that we're going to remove it
710 			TRACE(("  remove ARP entry %p!\n", entry));
711 
712 			MutexLocker locker(sCacheLock);
713 			if ((entry->flags & ARP_FLAG_REMOVED) != 0) {
714 				// The entry has already been removed, and is about to be
715 				// deleted
716 				break;
717 			}
718 
719 			hash_remove(sCache, entry);
720 			locker.Unlock();
721 
722 			delete entry;
723 			break;
724 		}
725 
726 		default:
727 		{
728 			if (entry->timer_state > ARP_STATE_LAST_REQUEST
729 				|| entry->protocol == NULL)
730 				break;
731 
732 			TRACE(("  send request for ARP entry %p!\n", entry));
733 
734 			net_buffer *request = get_request_buffer(entry);
735 			if (request == NULL)
736 				break;
737 
738 			if (entry->timer_state < ARP_STATE_LAST_REQUEST) {
739 				// we'll still need our buffer, so in order to prevent it being
740 				// freed by a successful send, we need to clone it
741 				net_buffer* clone = gBufferModule->clone(request, true);
742 				if (clone == NULL) {
743 					// cloning failed - that means we won't be able to send as
744 					// many requests as originally planned
745 					entry->timer_state = ARP_STATE_LAST_REQUEST;
746 				} else {
747 					put_request_buffer(entry, request);
748 					request = clone;
749 				}
750 			}
751 
752 			// we're trying to resolve the address, so keep sending requests
753 			status_t status = entry->protocol->next->module->send_data(
754 				entry->protocol->next, request);
755 			if (status < B_OK)
756 				gBufferModule->free(request);
757 
758 			entry->timer_state++;
759 			sStackModule->set_timer(&entry->timer, ARP_REQUEST_TIMEOUT);
760 			break;
761 		}
762 	}
763 }
764 
765 
766 /*!	Address resolver function: prepares and triggers the ARP request necessary
767 	to retrieve the hardware address for \a address.
768 
769 	You need to have the sCacheLock held when calling this function.
770 */
771 static status_t
772 arp_start_resolve(arp_protocol* protocol, in_addr_t address, arp_entry** _entry)
773 {
774 	ASSERT_LOCKED_MUTEX(&sCacheLock);
775 
776 	// create an unresolved ARP entry as a placeholder
777 	arp_entry *entry = arp_entry::Add(address, NULL, 0);
778 	if (entry == NULL)
779 		return B_NO_MEMORY;
780 
781 	// prepare ARP request
782 
783 	entry->request_buffer = gBufferModule->create(256);
784 	if (entry->request_buffer == NULL) {
785 		entry->ScheduleRemoval();
786 		return B_NO_MEMORY;
787 	}
788 
789 	NetBufferPrepend<arp_header> bufferHeader(entry->request_buffer);
790 	status_t status = bufferHeader.Status();
791 	if (status < B_OK) {
792 		entry->ScheduleRemoval();
793 		return status;
794 	}
795 
796 	// prepare ARP header
797 
798 	net_device *device = protocol->interface->device;
799 	arp_header &header = bufferHeader.Data();
800 
801 	header.hardware_type = htons(ARP_HARDWARE_TYPE_ETHER);
802 	header.protocol_type = htons(ETHER_TYPE_IP);
803 	header.hardware_length = ETHER_ADDRESS_LENGTH;
804 	header.protocol_length = sizeof(in_addr_t);
805 	header.opcode = htons(ARP_OPCODE_REQUEST);
806 
807 	memcpy(header.hardware_sender, device->address.data, ETHER_ADDRESS_LENGTH);
808 	memset(header.hardware_target, 0, ETHER_ADDRESS_LENGTH);
809 	header.protocol_sender = protocol->local_address;
810 	header.protocol_target = address;
811 
812 	// prepare source and target addresses
813 
814 	struct sockaddr_dl &source = *(struct sockaddr_dl *)
815 		entry->request_buffer->source;
816 	source.sdl_len = sizeof(sockaddr_dl);
817 	source.sdl_family = AF_LINK;
818 	source.sdl_index = device->index;
819 	source.sdl_type = IFT_ETHER;
820 	source.sdl_e_type = ETHER_TYPE_ARP;
821 	source.sdl_nlen = source.sdl_slen = 0;
822 	source.sdl_alen = ETHER_ADDRESS_LENGTH;
823 	memcpy(source.sdl_data, device->address.data, ETHER_ADDRESS_LENGTH);
824 
825 	entry->request_buffer->flags = MSG_BCAST;
826 		// this is a broadcast packet, we don't need to fill in the destination
827 
828 	entry->protocol = protocol;
829 	entry->timer_state = ARP_STATE_REQUEST;
830 	sStackModule->set_timer(&entry->timer, 0);
831 		// start request timer
832 
833 	*_entry = entry;
834 	return B_OK;
835 }
836 
837 
838 static status_t
839 arp_control(const char *subsystem, uint32 function, void *buffer,
840 	size_t bufferSize)
841 {
842 	struct arp_control control;
843 	if (bufferSize != sizeof(struct arp_control))
844 		return B_BAD_VALUE;
845 	if (user_memcpy(&control, buffer, sizeof(struct arp_control)) < B_OK)
846 		return B_BAD_ADDRESS;
847 
848 	MutexLocker locker(sCacheLock);
849 
850 	switch (function) {
851 		case ARP_SET_ENTRY:
852 		{
853 			sockaddr_dl hardwareAddress;
854 
855 			hardwareAddress.sdl_len = sizeof(sockaddr_dl);
856 			hardwareAddress.sdl_family = AF_LINK;
857 			hardwareAddress.sdl_index = 0;
858 			hardwareAddress.sdl_type = IFT_ETHER;
859 			hardwareAddress.sdl_e_type = ETHER_TYPE_IP;
860 			hardwareAddress.sdl_nlen = hardwareAddress.sdl_slen = 0;
861 			hardwareAddress.sdl_alen = ETHER_ADDRESS_LENGTH;
862 			memcpy(hardwareAddress.sdl_data, control.ethernet_address,
863 				ETHER_ADDRESS_LENGTH);
864 
865 			return arp_update_entry(control.address, &hardwareAddress,
866 				control.flags & (ARP_FLAG_PUBLISH | ARP_FLAG_PERMANENT
867 					| ARP_FLAG_REJECT));
868 		}
869 
870 		case ARP_GET_ENTRY:
871 		{
872 			arp_entry *entry = arp_entry::Lookup(control.address);
873 			if (entry == NULL || !(entry->flags & ARP_FLAG_VALID))
874 				return B_ENTRY_NOT_FOUND;
875 
876 			if (entry->hardware_address.sdl_alen == ETHER_ADDRESS_LENGTH) {
877 				memcpy(control.ethernet_address,
878 					entry->hardware_address.sdl_data, ETHER_ADDRESS_LENGTH);
879 			} else
880 				memset(control.ethernet_address, 0, ETHER_ADDRESS_LENGTH);
881 
882 			control.flags = entry->flags & ARP_PUBLIC_FLAG_MASK;
883 			return user_memcpy(buffer, &control, sizeof(struct arp_control));
884 		}
885 
886 		case ARP_GET_ENTRIES:
887 		{
888 			hash_iterator iterator;
889 			hash_open(sCache, &iterator);
890 
891 			arp_entry *entry;
892 			uint32 i = 0;
893 			while ((entry = (arp_entry *)hash_next(sCache, &iterator)) != NULL
894 				&& i < control.cookie) {
895 				i++;
896 			}
897 			hash_close(sCache, &iterator, false);
898 
899 			if (entry == NULL)
900 				return B_ENTRY_NOT_FOUND;
901 
902 			control.cookie++;
903 			control.address = entry->protocol_address;
904 			if (entry->hardware_address.sdl_alen == ETHER_ADDRESS_LENGTH) {
905 				memcpy(control.ethernet_address,
906 					entry->hardware_address.sdl_data, ETHER_ADDRESS_LENGTH);
907 			} else
908 				memset(control.ethernet_address, 0, ETHER_ADDRESS_LENGTH);
909 			control.flags = entry->flags & ARP_PUBLIC_FLAG_MASK;
910 
911 			return user_memcpy(buffer, &control, sizeof(struct arp_control));
912 		}
913 
914 		case ARP_DELETE_ENTRY:
915 		{
916 			arp_entry *entry = arp_entry::Lookup(control.address);
917 			if (entry == NULL)
918 				return B_ENTRY_NOT_FOUND;
919 			if ((entry->flags & ARP_FLAG_LOCAL) != 0)
920 				return B_BAD_VALUE;
921 
922 			entry->ScheduleRemoval();
923 			return B_OK;
924 		}
925 
926 		case ARP_FLUSH_ENTRIES:
927 		{
928 			hash_iterator iterator;
929 			hash_open(sCache, &iterator);
930 
931 			arp_entry *entry;
932 			while ((entry = (arp_entry *)hash_next(sCache, &iterator)) != NULL) {
933 				// we never flush local ARP entries
934 				if ((entry->flags & ARP_FLAG_LOCAL) != 0)
935 					continue;
936 
937 				entry->ScheduleRemoval();
938 			}
939 			hash_close(sCache, &iterator, false);
940 			return B_OK;
941 		}
942 
943 		case ARP_IGNORE_REPLIES:
944 			sIgnoreReplies = control.flags != 0;
945 			return B_OK;
946 	}
947 
948 	return B_BAD_VALUE;
949 }
950 
951 
952 static status_t
953 arp_init()
954 {
955 	mutex_init(&sCacheLock, "arp cache");
956 
957 	sCache = hash_init(64, offsetof(struct arp_entry, next),
958 		&arp_entry::Compare, &arp_entry::Hash);
959 	if (sCache == NULL) {
960 		mutex_destroy(&sCacheLock);
961 		return B_NO_MEMORY;
962 	}
963 
964 	register_generic_syscall(ARP_SYSCALLS, arp_control, 1, 0);
965 	return B_OK;
966 }
967 
968 
969 static status_t
970 arp_uninit()
971 {
972 	unregister_generic_syscall(ARP_SYSCALLS, 1);
973 	return B_OK;
974 }
975 
976 
977 //	#pragma mark - net_datalink_protocol
978 
979 
980 status_t
981 arp_init_protocol(net_interface* interface, net_domain* domain,
982 	net_datalink_protocol** _protocol)
983 {
984 	// We currently only support a single family and type!
985 	if (interface->device->type != IFT_ETHER
986 		|| domain->family != AF_INET)
987 		return B_BAD_TYPE;
988 
989 	status_t status = sStackModule->register_device_handler(interface->device,
990 		B_NET_FRAME_TYPE(IFT_ETHER, ETHER_TYPE_ARP), &arp_receive, NULL);
991 	if (status != B_OK)
992 		return status;
993 
994 	status = sStackModule->register_domain_device_handler(
995 		interface->device, B_NET_FRAME_TYPE(IFT_ETHER, ETHER_TYPE_IP), domain);
996 	if (status != B_OK)
997 		return status;
998 
999 	arp_protocol* protocol = new(std::nothrow) arp_protocol;
1000 	if (protocol == NULL)
1001 		return B_NO_MEMORY;
1002 
1003 	memset(&protocol->hardware_address, 0, sizeof(sockaddr_dl));
1004 	protocol->local_address = 0;
1005 
1006 	*_protocol = protocol;
1007 	return B_OK;
1008 }
1009 
1010 
1011 status_t
1012 arp_uninit_protocol(net_datalink_protocol *protocol)
1013 {
1014 	sStackModule->unregister_device_handler(protocol->interface->device,
1015 		B_NET_FRAME_TYPE(IFT_ETHER, ETHER_TYPE_ARP));
1016 	sStackModule->unregister_device_handler(protocol->interface->device,
1017 		B_NET_FRAME_TYPE(IFT_ETHER, ETHER_TYPE_IP));
1018 
1019 	delete protocol;
1020 	return B_OK;
1021 }
1022 
1023 
1024 status_t
1025 arp_send_data(net_datalink_protocol *_protocol, net_buffer *buffer)
1026 {
1027 	arp_protocol *protocol = (arp_protocol *)_protocol;
1028 	{
1029 		MutexLocker locker(sCacheLock);
1030 
1031 		// Set buffer target and destination address
1032 
1033 		memcpy(buffer->source, &protocol->hardware_address,
1034 			protocol->hardware_address.sdl_len);
1035 
1036 		if ((buffer->flags & MSG_MCAST) != 0) {
1037 			sockaddr_dl multicastDestination;
1038 			ipv4_to_ether_multicast(&multicastDestination,
1039 				(sockaddr_in *)buffer->destination);
1040 			memcpy(buffer->destination, &multicastDestination,
1041 				sizeof(multicastDestination));
1042 		} else if ((buffer->flags & MSG_BCAST) == 0) {
1043 			// Lookup destination (we may need to wait for this)
1044 			arp_entry *entry = arp_entry::Lookup(
1045 				((struct sockaddr_in *)buffer->destination)->sin_addr.s_addr);
1046 			if (entry == NULL) {
1047 				status_t status = arp_start_resolve(protocol,
1048 					((struct sockaddr_in*)buffer->destination)->sin_addr.s_addr,
1049 					&entry);
1050 				if (status != B_OK)
1051 					return status;
1052 			}
1053 
1054 			if ((entry->flags & ARP_FLAG_REJECT) != 0)
1055 				return EHOSTUNREACH;
1056 
1057 			if ((entry->flags & ARP_FLAG_VALID) == 0) {
1058 				// entry is still being resolved.
1059 				TRACE(("ARP Queuing packet %p, entry still being resolved.\n",
1060 					buffer));
1061 				entry->queue.Add(buffer);
1062 				return B_OK;
1063 			}
1064 
1065 			memcpy(buffer->destination, &entry->hardware_address,
1066 				entry->hardware_address.sdl_len);
1067 		}
1068 		// the broadcast address is set in the ethernet frame module
1069 	}
1070 	TRACE(("%s(%p): from %s\n", __FUNCTION__, buffer,
1071 		mac_to_string(LLADDR((sockaddr_dl*)buffer->source))));
1072 	TRACE(("  to %s\n",
1073 		mac_to_string(LLADDR((sockaddr_dl*)buffer->destination))));
1074 
1075 	return protocol->next->module->send_data(protocol->next, buffer);
1076 }
1077 
1078 
1079 status_t
1080 arp_up(net_datalink_protocol* _protocol)
1081 {
1082 	arp_protocol* protocol = (arp_protocol*)_protocol;
1083 	status_t status = protocol->next->module->interface_up(protocol->next);
1084 	if (status != B_OK)
1085 		return status;
1086 
1087 	// cache this device's address for later use
1088 
1089 	status = arp_update_local(protocol);
1090 	if (status != B_OK) {
1091 		protocol->next->module->interface_down(protocol->next);
1092 		return status;
1093 	}
1094 
1095 	return B_OK;
1096 }
1097 
1098 
1099 void
1100 arp_down(net_datalink_protocol *protocol)
1101 {
1102 	// remove local ARP entries from the cache
1103 	arp_remove_local((arp_protocol*)protocol);
1104 
1105 	protocol->next->module->interface_down(protocol->next);
1106 }
1107 
1108 
1109 status_t
1110 arp_change_address(net_datalink_protocol* _protocol,
1111 	net_interface_address* address, int32 option,
1112 	const struct sockaddr* oldAddress, const struct sockaddr* newAddress)
1113 {
1114 	arp_protocol* protocol = (arp_protocol*)_protocol;
1115 	TRACE(("%s(option %" B_PRId32 ")\n", __FUNCTION__, option));
1116 
1117 	switch (option) {
1118 		case SIOCSIFADDR:
1119 		case SIOCAIFADDR:
1120 		case SIOCDIFADDR:
1121 			// Those are the options we handle
1122 			if ((protocol->interface->flags & IFF_UP) != 0) {
1123 				// Update ARP entry for the local address
1124 
1125 				if (newAddress != NULL && newAddress->sa_family == AF_INET) {
1126 					status_t status = arp_set_local_entry(protocol, newAddress);
1127 					if (status != B_OK)
1128 						return status;
1129 				}
1130 
1131 				if (option != SIOCAIFADDR
1132 					&& (oldAddress == NULL || oldAddress->sa_family == AF_INET))
1133 					arp_remove_local_entry(protocol, oldAddress, true);
1134 			}
1135 			break;
1136 
1137 		default:
1138 			break;
1139 	}
1140 
1141 	return protocol->next->module->change_address(protocol->next, address,
1142 		option, oldAddress, newAddress);
1143 }
1144 
1145 
1146 status_t
1147 arp_control(net_datalink_protocol *_protocol, int32 op, void *argument,
1148 	size_t length)
1149 {
1150 	arp_protocol* protocol = (arp_protocol*)_protocol;
1151 	return protocol->next->module->control(protocol->next, op, argument,
1152 		length);
1153 }
1154 
1155 
1156 static status_t
1157 arp_join_multicast(net_datalink_protocol *protocol, const sockaddr *address)
1158 {
1159 	if (address->sa_family != AF_INET)
1160 		return EINVAL;
1161 
1162 	sockaddr_dl multicastAddress;
1163 	ipv4_to_ether_multicast(&multicastAddress, (const sockaddr_in *)address);
1164 
1165 	return protocol->next->module->join_multicast(protocol->next,
1166 		(sockaddr *)&multicastAddress);
1167 }
1168 
1169 
1170 static status_t
1171 arp_leave_multicast(net_datalink_protocol *protocol, const sockaddr *address)
1172 {
1173 	if (address->sa_family != AF_INET)
1174 		return EINVAL;
1175 
1176 	sockaddr_dl multicastAddress;
1177 	ipv4_to_ether_multicast(&multicastAddress, (const sockaddr_in *)address);
1178 
1179 	return protocol->next->module->leave_multicast(protocol->next,
1180 		(sockaddr *)&multicastAddress);
1181 }
1182 
1183 
1184 static status_t
1185 arp_std_ops(int32 op, ...)
1186 {
1187 	switch (op) {
1188 		case B_MODULE_INIT:
1189 			return arp_init();
1190 		case B_MODULE_UNINIT:
1191 			return arp_uninit();
1192 
1193 		default:
1194 			return B_ERROR;
1195 	}
1196 }
1197 
1198 
1199 static net_datalink_protocol_module_info sARPModule = {
1200 	{
1201 		"network/datalink_protocols/arp/v1",
1202 		0,
1203 		arp_std_ops
1204 	},
1205 	arp_init_protocol,
1206 	arp_uninit_protocol,
1207 	arp_send_data,
1208 	arp_up,
1209 	arp_down,
1210 	arp_change_address,
1211 	arp_control,
1212 	arp_join_multicast,
1213 	arp_leave_multicast,
1214 };
1215 
1216 
1217 module_dependency module_dependencies[] = {
1218 	{NET_STACK_MODULE_NAME, (module_info**)&sStackModule},
1219 	{NET_DATALINK_MODULE_NAME, (module_info**)&sDatalinkModule},
1220 	{NET_BUFFER_MODULE_NAME, (module_info**)&gBufferModule},
1221 	{}
1222 };
1223 
1224 module_info* modules[] = {
1225 	(module_info*)&sARPModule,
1226 	NULL
1227 };
1228