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