xref: /haiku/src/add-ons/kernel/network/protocols/udp/udp.cpp (revision c9060eb991e10e477ece52478d6743fc7691c143)
1 /*
2  * Copyright 2006-2008, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Oliver Tappe, zooey@hirschkaefer.de
7  *		Hugo Santos, hugosantos@gmail.com
8  */
9 
10 
11 #include <net_buffer.h>
12 #include <net_datalink.h>
13 #include <net_protocol.h>
14 #include <net_stack.h>
15 
16 #include <lock.h>
17 #include <util/AutoLock.h>
18 #include <util/DoublyLinkedList.h>
19 #include <util/OpenHashTable.h>
20 
21 #include <KernelExport.h>
22 
23 #include <NetBufferUtilities.h>
24 #include <NetUtilities.h>
25 #include <ProtocolUtilities.h>
26 
27 #include <netinet/in.h>
28 #include <new>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <utility>
32 
33 
34 // NOTE the locking protocol dictates that we must hold UdpDomainSupport's
35 //      lock before holding a child UdpEndpoint's lock. This restriction
36 //      is dictated by the receive path as blind access to the endpoint
37 //      hash is required when holding the DomainSuppport's lock.
38 
39 
40 //#define TRACE_UDP
41 #ifdef TRACE_UDP
42 #	define TRACE_BLOCK(x) dump_block x
43 // do not remove the space before ', ##args' if you want this
44 // to compile with gcc 2.95
45 #	define TRACE_EP(format, args...)	dprintf("UDP [%llu] %p " format "\n", \
46 		system_time(), this , ##args)
47 #	define TRACE_EPM(format, args...)	dprintf("UDP [%llu] " format "\n", \
48 		system_time() , ##args)
49 #	define TRACE_DOMAIN(format, args...)	dprintf("UDP [%llu] (%d) " format \
50 		"\n", system_time(), Domain()->family , ##args)
51 #else
52 #	define TRACE_BLOCK(x)
53 #	define TRACE_EP(args...)	do { } while (0)
54 #	define TRACE_EPM(args...)	do { } while (0)
55 #	define TRACE_DOMAIN(args...)	do { } while (0)
56 #endif
57 
58 
59 struct udp_header {
60 	uint16 source_port;
61 	uint16 destination_port;
62 	uint16 udp_length;
63 	uint16 udp_checksum;
64 } _PACKED;
65 
66 
67 typedef NetBufferField<uint16, offsetof(udp_header, udp_checksum)>
68 	UDPChecksumField;
69 
70 class UdpDomainSupport;
71 
72 class UdpEndpoint : public net_protocol, public DatagramSocket<> {
73 public:
74 	UdpEndpoint(net_socket *socket);
75 
76 	status_t				Bind(const sockaddr *newAddr);
77 	status_t				Unbind(sockaddr *newAddr);
78 	status_t				Connect(const sockaddr *newAddr);
79 
80 	status_t				Open();
81 	status_t				Close();
82 	status_t				Free();
83 
84 	status_t				SendRoutedData(net_buffer *buffer, net_route *route);
85 	status_t				SendData(net_buffer *buffer);
86 
87 	ssize_t					BytesAvailable();
88 	status_t				FetchData(size_t numBytes, uint32 flags,
89 								net_buffer **_buffer);
90 
91 	status_t				StoreData(net_buffer *buffer);
92 	status_t				DeliverData(net_buffer *buffer);
93 
94 	// only the domain support will change/check the Active flag so
95 	// we don't really need to protect it with the socket lock.
96 	bool					IsActive() const { return fActive; }
97 	void					SetActive(bool newValue) { fActive = newValue; }
98 
99 	HashTableLink<UdpEndpoint> *HashTableLink() { return &fLink; }
100 
101 private:
102 	UdpDomainSupport		*fManager;
103 	bool					fActive;
104 								// an active UdpEndpoint is part of the endpoint
105 								// hash (and it is bound and optionally connected)
106 
107 	::HashTableLink<UdpEndpoint> fLink;
108 };
109 
110 
111 class UdpDomainSupport;
112 
113 struct UdpHashDefinition {
114 	typedef net_address_module_info ParentType;
115 	typedef std::pair<const sockaddr *, const sockaddr *> KeyType;
116 	typedef UdpEndpoint ValueType;
117 
118 	UdpHashDefinition(net_address_module_info *_module)
119 		: module(_module) {}
120 	UdpHashDefinition(const UdpHashDefinition& definition)
121 		: module(definition.module) {}
122 
123 	size_t HashKey(const KeyType &key) const
124 	{
125 		return _Mix(module->hash_address_pair(key.first, key.second));
126 	}
127 
128 	size_t Hash(UdpEndpoint *endpoint) const
129 	{
130 		return _Mix(endpoint->LocalAddress().HashPair(*endpoint->PeerAddress()));
131 	}
132 
133 	static size_t _Mix(size_t hash)
134 	{
135 		// move the bits into the relevant range (as defined by kNumHashBuckets):
136 		return (hash & 0x000007FF) ^ (hash & 0x003FF800) >> 11
137 			^ (hash & 0xFFC00000UL) >> 22;
138 	}
139 
140 	bool Compare(const KeyType &key, UdpEndpoint *endpoint) const
141 	{
142 		return endpoint->LocalAddress().EqualTo(key.first, true)
143 			&& endpoint->PeerAddress().EqualTo(key.second, true);
144 	}
145 
146 	HashTableLink<UdpEndpoint> *GetLink(UdpEndpoint *endpoint) const
147 	{
148 		return endpoint->HashTableLink();
149 	}
150 
151 	net_address_module_info *module;
152 };
153 
154 
155 class UdpDomainSupport : public DoublyLinkedListLinkImpl<UdpDomainSupport> {
156 public:
157 	UdpDomainSupport(net_domain *domain);
158 	~UdpDomainSupport();
159 
160 	status_t Init();
161 
162 	net_domain *Domain() const { return fDomain; }
163 
164 	void Ref() { fEndpointCount++; }
165 	bool Put() { fEndpointCount--; return fEndpointCount == 0; }
166 
167 	status_t DemuxIncomingBuffer(net_buffer *buffer);
168 
169 	status_t BindEndpoint(UdpEndpoint *endpoint, const sockaddr *address);
170 	status_t ConnectEndpoint(UdpEndpoint *endpoint, const sockaddr *address);
171 	status_t UnbindEndpoint(UdpEndpoint *endpoint);
172 
173 	void DumpEndpoints() const;
174 
175 private:
176 	status_t _BindEndpoint(UdpEndpoint *endpoint, const sockaddr *address);
177 	status_t _Bind(UdpEndpoint *endpoint, const sockaddr *address);
178 	status_t _BindToEphemeral(UdpEndpoint *endpoint, const sockaddr *address);
179 	status_t _FinishBind(UdpEndpoint *endpoint, const sockaddr *address);
180 
181 	UdpEndpoint *_FindActiveEndpoint(const sockaddr *ourAddress,
182 		const sockaddr *peerAddress);
183 	status_t _DemuxBroadcast(net_buffer *buffer);
184 	status_t _DemuxUnicast(net_buffer *buffer);
185 
186 	uint16 _GetNextEphemeral();
187 	UdpEndpoint *_EndpointWithPort(uint16 port) const;
188 
189 	net_address_module_info *AddressModule() const
190 		{ return fDomain->address_module; }
191 
192 	typedef OpenHashTable<UdpHashDefinition, false> EndpointTable;
193 
194 	mutex			fLock;
195 	net_domain		*fDomain;
196 	uint16			fLastUsedEphemeral;
197 	EndpointTable	fActiveEndpoints;
198 	uint32			fEndpointCount;
199 
200 	static const uint16		kFirst = 49152;
201 	static const uint16		kLast = 65535;
202 	static const uint32		kNumHashBuckets = 0x800;
203 							// if you change this, adjust the shifting in
204 							// Hash() accordingly!
205 };
206 
207 
208 typedef DoublyLinkedList<UdpDomainSupport> UdpDomainList;
209 
210 
211 class UdpEndpointManager {
212 public:
213 	UdpEndpointManager();
214 	~UdpEndpointManager();
215 
216 	status_t		ReceiveData(net_buffer *buffer);
217 	status_t		Deframe(net_buffer *buffer);
218 
219 	UdpDomainSupport *OpenEndpoint(UdpEndpoint *endpoint);
220 	status_t FreeEndpoint(UdpDomainSupport *domain);
221 
222 	status_t		InitCheck() const;
223 
224 	static int DumpEndpoints(int argc, char *argv[]);
225 
226 private:
227 	UdpDomainSupport *_GetDomain(net_domain *domain, bool create);
228 
229 	mutex			fLock;
230 	status_t		fStatus;
231 	UdpDomainList	fDomains;
232 };
233 
234 
235 static UdpEndpointManager *sUdpEndpointManager;
236 
237 net_buffer_module_info *gBufferModule;
238 net_datalink_module_info *gDatalinkModule;
239 net_stack_module_info *gStackModule;
240 
241 
242 // #pragma mark -
243 
244 
245 UdpDomainSupport::UdpDomainSupport(net_domain *domain)
246 	:
247 	fDomain(domain),
248 	fActiveEndpoints(domain->address_module),
249 	fEndpointCount(0)
250 {
251 	mutex_init(&fLock, "udp domain");
252 
253 	fLastUsedEphemeral = kFirst + rand() % (kLast - kFirst);
254 }
255 
256 
257 UdpDomainSupport::~UdpDomainSupport()
258 {
259 	mutex_destroy(&fLock);
260 }
261 
262 
263 status_t
264 UdpDomainSupport::Init()
265 {
266 	return fActiveEndpoints.Init(kNumHashBuckets);
267 }
268 
269 
270 status_t
271 UdpDomainSupport::DemuxIncomingBuffer(net_buffer *buffer)
272 {
273 	// NOTE multicast is delivered directly to the endpoint
274 
275 	MutexLocker _(fLock);
276 
277 	if (buffer->flags & MSG_BCAST)
278 		return _DemuxBroadcast(buffer);
279 	else if (buffer->flags & MSG_MCAST)
280 		return B_ERROR;
281 
282 	return _DemuxUnicast(buffer);
283 }
284 
285 
286 status_t
287 UdpDomainSupport::BindEndpoint(UdpEndpoint *endpoint,
288 	const sockaddr *address)
289 {
290 	MutexLocker _(fLock);
291 
292 	if (endpoint->IsActive())
293 		return EINVAL;
294 
295 	return _BindEndpoint(endpoint, address);
296 }
297 
298 
299 status_t
300 UdpDomainSupport::ConnectEndpoint(UdpEndpoint *endpoint,
301 	const sockaddr *address)
302 {
303 	MutexLocker _(fLock);
304 
305 	if (endpoint->IsActive()) {
306 		fActiveEndpoints.Remove(endpoint);
307 		endpoint->SetActive(false);
308 	}
309 
310 	if (address->sa_family == AF_UNSPEC) {
311 		// [Stevens-UNP1, p226]: specifying AF_UNSPEC requests a "disconnect",
312 		// so we reset the peer address:
313 		endpoint->PeerAddress().SetToEmpty();
314 	} else {
315 		status_t status = endpoint->PeerAddress().SetTo(address);
316 		if (status < B_OK)
317 			return status;
318 	}
319 
320 	// we need to activate no matter whether or not we have just disconnected,
321 	// as calling connect() always triggers an implicit bind():
322 	return _BindEndpoint(endpoint, *endpoint->LocalAddress());
323 }
324 
325 
326 status_t
327 UdpDomainSupport::UnbindEndpoint(UdpEndpoint *endpoint)
328 {
329 	MutexLocker _(fLock);
330 
331 	if (endpoint->IsActive())
332 		fActiveEndpoints.Remove(endpoint);
333 
334 	endpoint->SetActive(false);
335 
336 	return B_OK;
337 }
338 
339 
340 void
341 UdpDomainSupport::DumpEndpoints() const
342 {
343 	kprintf("-------- UDP Domain %p ---------\n", this);
344 	kprintf("%10s %20s %20s %8s\n", "address", "local", "peer", "recv-q");
345 
346 	EndpointTable::Iterator it = fActiveEndpoints.GetIterator();
347 
348 	while (it.HasNext()) {
349 		UdpEndpoint *endpoint = it.Next();
350 
351 		char localBuf[64], peerBuf[64];
352 		endpoint->LocalAddress().AsString(localBuf, sizeof(localBuf), true);
353 		endpoint->PeerAddress().AsString(peerBuf, sizeof(peerBuf), true);
354 
355 		kprintf("%p %20s %20s %8lu\n", endpoint, localBuf, peerBuf,
356 			endpoint->AvailableData());
357 	}
358 }
359 
360 
361 status_t
362 UdpDomainSupport::_BindEndpoint(UdpEndpoint *endpoint,
363 	const sockaddr *address)
364 {
365 	if (AddressModule()->get_port(address) == 0)
366 		return _BindToEphemeral(endpoint, address);
367 
368 	return _Bind(endpoint, address);
369 }
370 
371 
372 status_t
373 UdpDomainSupport::_Bind(UdpEndpoint *endpoint, const sockaddr *address)
374 {
375 	int socketOptions = endpoint->Socket()->options;
376 
377 	EndpointTable::Iterator it = fActiveEndpoints.GetIterator();
378 
379 	// Iterate over all active UDP-endpoints and check if the requested bind
380 	// is allowed (see figure 22.24 in [Stevens - TCP2, p735]):
381 	TRACE_DOMAIN("CheckBindRequest() for %s...", AddressString(fDomain,
382 		address, true).Data());
383 
384 	while (it.HasNext()) {
385 		UdpEndpoint *otherEndpoint = it.Next();
386 
387 		TRACE_DOMAIN("  ...checking endpoint %p (port=%u)...", otherEndpoint,
388 			ntohs(otherEndpoint->LocalAddress().Port()));
389 
390 		if (otherEndpoint->LocalAddress().EqualPorts(address)) {
391 			// port is already bound, SO_REUSEADDR or SO_REUSEPORT is required:
392 			if (otherEndpoint->Socket()->options & (SO_REUSEADDR | SO_REUSEPORT) == 0
393 				|| socketOptions & (SO_REUSEADDR | SO_REUSEPORT) == 0)
394 				return EADDRINUSE;
395 
396 			// if both addresses are the same, SO_REUSEPORT is required:
397 			if (otherEndpoint->LocalAddress().EqualTo(address, false)
398 				&& (otherEndpoint->Socket()->options & SO_REUSEPORT == 0
399 					|| socketOptions & SO_REUSEPORT == 0))
400 				return EADDRINUSE;
401 		}
402 	}
403 
404 	return _FinishBind(endpoint, address);
405 }
406 
407 
408 status_t
409 UdpDomainSupport::_BindToEphemeral(UdpEndpoint *endpoint,
410 	const sockaddr *address)
411 {
412 	SocketAddressStorage newAddress(AddressModule());
413 	status_t status = newAddress.SetTo(address);
414 	if (status < B_OK)
415 		return status;
416 
417 	uint16 allocedPort = _GetNextEphemeral();
418 	if (allocedPort == 0)
419 		return ENOBUFS;
420 
421 	newAddress.SetPort(allocedPort);
422 
423 	return _FinishBind(endpoint, *newAddress);
424 }
425 
426 
427 status_t
428 UdpDomainSupport::_FinishBind(UdpEndpoint *endpoint, const sockaddr *address)
429 {
430 	status_t status = endpoint->next->module->bind(endpoint->next, address);
431 	if (status < B_OK)
432 		return status;
433 
434 	fActiveEndpoints.Insert(endpoint);
435 	endpoint->SetActive(true);
436 
437 	return B_OK;
438 }
439 
440 
441 UdpEndpoint *
442 UdpDomainSupport::_FindActiveEndpoint(const sockaddr *ourAddress,
443 	const sockaddr *peerAddress)
444 {
445 	TRACE_DOMAIN("finding Endpoint for %s -> %s",
446 		AddressString(fDomain, ourAddress, true).Data(),
447 		AddressString(fDomain, peerAddress, true).Data());
448 
449 	return fActiveEndpoints.Lookup(std::make_pair(ourAddress, peerAddress));
450 }
451 
452 
453 status_t
454 UdpDomainSupport::_DemuxBroadcast(net_buffer *buffer)
455 {
456 	sockaddr *peerAddr = buffer->source;
457 	sockaddr *broadcastAddr = buffer->destination;
458 	sockaddr *mask = NULL;
459 	if (buffer->interface)
460 		mask = (sockaddr *)buffer->interface->mask;
461 
462 	TRACE_DOMAIN("_DemuxBroadcast(%p)", buffer);
463 
464 	uint16 incomingPort = AddressModule()->get_port(broadcastAddr);
465 
466 	EndpointTable::Iterator it = fActiveEndpoints.GetIterator();
467 
468 	while (it.HasNext()) {
469 		UdpEndpoint *endpoint = it.Next();
470 
471 		TRACE_DOMAIN("  _DemuxBroadcast(): checking endpoint %s...",
472 			AddressString(fDomain, *endpoint->LocalAddress(), true).Data());
473 
474 		if (endpoint->LocalAddress().Port() != incomingPort) {
475 			// ports don't match, so we do not dispatch to this endpoint...
476 			continue;
477 		}
478 
479 		if (!endpoint->PeerAddress().IsEmpty(true)) {
480 			// endpoint is connected to a specific destination, we check if
481 			// this datagram is from there:
482 			if (!endpoint->PeerAddress().EqualTo(peerAddr, true)) {
483 				// no, datagram is from another peer, so we do not dispatch to
484 				// this endpoint...
485 				continue;
486 			}
487 		}
488 
489 		if (endpoint->LocalAddress().MatchMasked(broadcastAddr, mask)
490 			|| endpoint->LocalAddress().IsEmpty(false)) {
491 			// address matches, dispatch to this endpoint:
492 			endpoint->StoreData(buffer);
493 		}
494 	}
495 
496 	return B_OK;
497 }
498 
499 
500 status_t
501 UdpDomainSupport::_DemuxUnicast(net_buffer *buffer)
502 {
503 	struct sockaddr *peerAddr = buffer->source;
504 	struct sockaddr *localAddr = buffer->destination;
505 
506 	TRACE_DOMAIN("_DemuxUnicast(%p)", buffer);
507 
508 	UdpEndpoint *endpoint;
509 	// look for full (most special) match:
510 	endpoint = _FindActiveEndpoint(localAddr, peerAddr);
511 	if (!endpoint) {
512 		// look for endpoint matching local address & port:
513 		endpoint = _FindActiveEndpoint(localAddr, NULL);
514 		if (!endpoint) {
515 			// look for endpoint matching peer address & port and local port:
516 			SocketAddressStorage local(AddressModule());
517 			local.SetToEmpty();
518 			local.SetPort(AddressModule()->get_port(localAddr));
519 			endpoint = _FindActiveEndpoint(*local, peerAddr);
520 			if (!endpoint) {
521 				// last chance: look for endpoint matching local port only:
522 				endpoint = _FindActiveEndpoint(*local, NULL);
523 			}
524 		}
525 	}
526 
527 	if (!endpoint)
528 		return B_NAME_NOT_FOUND;
529 
530 	endpoint->StoreData(buffer);
531 	return B_OK;
532 }
533 
534 
535 uint16
536 UdpDomainSupport::_GetNextEphemeral()
537 {
538 	uint16 stop, curr;
539 	if (fLastUsedEphemeral < kLast) {
540 		stop = fLastUsedEphemeral;
541 		curr = fLastUsedEphemeral + 1;
542 	} else {
543 		stop = kLast;
544 		curr = kFirst;
545 	}
546 
547 	// TODO: a free list could be used to avoid the impact of these
548 	//       two nested loops most of the time... let's see how bad this really is
549 
550 	TRACE_DOMAIN("_GetNextEphemeral(), last %hu, curr %hu, stop %hu",
551 		fLastUsedEphemeral, curr, stop);
552 
553 	for (; curr != stop; curr = (curr < kLast) ? (curr + 1) : kFirst) {
554 		TRACE_DOMAIN("  _GetNextEphemeral(): trying port %hu...", curr);
555 
556 		if (_EndpointWithPort(htons(curr)) == NULL) {
557 			TRACE_DOMAIN("  _GetNextEphemeral(): ...using port %hu", curr);
558 			fLastUsedEphemeral = curr;
559 			return curr;
560 		}
561 	}
562 
563 	return 0;
564 }
565 
566 
567 UdpEndpoint *
568 UdpDomainSupport::_EndpointWithPort(uint16 port) const
569 {
570 	EndpointTable::Iterator it = fActiveEndpoints.GetIterator();
571 
572 	while (it.HasNext()) {
573 		UdpEndpoint *endpoint = it.Next();
574 		if (endpoint->LocalAddress().Port() == port)
575 			return endpoint;
576 	}
577 
578 	return NULL;
579 }
580 
581 
582 // #pragma mark -
583 
584 
585 UdpEndpointManager::UdpEndpointManager()
586 {
587 	mutex_init(&fLock, "UDP endpoints");
588 	fStatus = B_OK;
589 }
590 
591 
592 UdpEndpointManager::~UdpEndpointManager()
593 {
594 	mutex_destroy(&fLock);
595 }
596 
597 
598 status_t
599 UdpEndpointManager::InitCheck() const
600 {
601 	return fStatus;
602 }
603 
604 
605 int
606 UdpEndpointManager::DumpEndpoints(int argc, char *argv[])
607 {
608 	UdpDomainList::Iterator it = sUdpEndpointManager->fDomains.GetIterator();
609 
610 	while (it.HasNext())
611 		it.Next()->DumpEndpoints();
612 
613 	return 0;
614 }
615 
616 
617 // #pragma mark - inbound
618 
619 
620 status_t
621 UdpEndpointManager::ReceiveData(net_buffer *buffer)
622 {
623 	status_t status = Deframe(buffer);
624 	if (status < B_OK)
625 		return status;
626 
627 	TRACE_EPM("ReceiveData(%p [%ld bytes])", buffer, buffer->size);
628 
629 	net_domain *domain = buffer->interface->domain;
630 
631 	UdpDomainSupport *domainSupport = NULL;
632 
633 	{
634 		MutexLocker _(fLock);
635 		domainSupport = _GetDomain(domain, false);
636 		// TODO we don't want to hold to the manager's lock
637 		//      during the whole RX path, we may not hold an
638 		//      endpoint's lock with the manager lock held.
639 		//      But we should increase the domain's refcount
640 		//      here.
641 	}
642 
643 	if (domainSupport == NULL) {
644 		// we don't instantiate domain supports in the
645 		// RX path as we are only interested in delivering
646 		// data to existing sockets.
647 		return B_ERROR;
648 	}
649 
650 	status = domainSupport->DemuxIncomingBuffer(buffer);
651 	if (status < B_OK) {
652 		TRACE_EPM("  ReceiveData(): no endpoint.");
653 		// TODO: send ICMP-error
654 		return B_ERROR;
655 	}
656 
657 	gBufferModule->free(buffer);
658 	return B_OK;
659 }
660 
661 
662 status_t
663 UdpEndpointManager::Deframe(net_buffer *buffer)
664 {
665 	TRACE_EPM("Deframe(%p [%ld bytes])", buffer, buffer->size);
666 
667 	NetBufferHeaderReader<udp_header> bufferHeader(buffer);
668 	if (bufferHeader.Status() < B_OK)
669 		return bufferHeader.Status();
670 
671 	udp_header &header = bufferHeader.Data();
672 
673 	if (buffer->interface == NULL || buffer->interface->domain == NULL) {
674 		TRACE_EPM("  Deframe(): UDP packed dropped as there was no domain "
675 			"specified (interface %p).", buffer->interface);
676 		return B_BAD_VALUE;
677 	}
678 
679 	net_domain *domain = buffer->interface->domain;
680 	net_address_module_info *addressModule = domain->address_module;
681 
682 	SocketAddress source(addressModule, buffer->source);
683 	SocketAddress destination(addressModule, buffer->destination);
684 
685 	source.SetPort(header.source_port);
686 	destination.SetPort(header.destination_port);
687 
688 	TRACE_EPM("  Deframe(): data from %s to %s", source.AsString(true).Data(),
689 		destination.AsString(true).Data());
690 
691 	uint16 udpLength = ntohs(header.udp_length);
692 	if (udpLength > buffer->size) {
693 		TRACE_EPM("  Deframe(): buffer is too short, expected %hu.",
694 			udpLength);
695 		return B_MISMATCHED_VALUES;
696 	}
697 
698 	if (buffer->size > udpLength)
699 		gBufferModule->trim(buffer, udpLength);
700 
701 	if (header.udp_checksum != 0) {
702 		// check UDP-checksum (simulating a so-called "pseudo-header"):
703 		uint16 sum = Checksum::PseudoHeader(addressModule, gBufferModule,
704 			buffer, IPPROTO_UDP);
705 		if (sum != 0) {
706 			TRACE_EPM("  Deframe(): bad checksum 0x%hx.", sum);
707 			return B_BAD_VALUE;
708 		}
709 	}
710 
711 	bufferHeader.Remove();
712 		// remove UDP-header from buffer before passing it on
713 
714 	return B_OK;
715 }
716 
717 
718 UdpDomainSupport *
719 UdpEndpointManager::OpenEndpoint(UdpEndpoint *endpoint)
720 {
721 	MutexLocker _(fLock);
722 
723 	UdpDomainSupport *domain = _GetDomain(endpoint->Domain(), true);
724 	if (domain)
725 		domain->Ref();
726 	return domain;
727 }
728 
729 
730 status_t
731 UdpEndpointManager::FreeEndpoint(UdpDomainSupport *domain)
732 {
733 	MutexLocker _(fLock);
734 
735 	if (domain->Put()) {
736 		fDomains.Remove(domain);
737 		delete domain;
738 	}
739 
740 	return B_OK;
741 }
742 
743 
744 // #pragma mark -
745 
746 
747 UdpDomainSupport *
748 UdpEndpointManager::_GetDomain(net_domain *domain, bool create)
749 {
750 	UdpDomainList::Iterator it = fDomains.GetIterator();
751 
752 	// TODO convert this into a Hashtable or install per-domain
753 	//      receiver handlers that forward the requests to the
754 	//      appropriate DemuxIncomingBuffer(). For instance, while
755 	//      being constructed UdpDomainSupport could call
756 	//      register_domain_receiving_protocol() with the right
757 	//      family.
758 	while (it.HasNext()) {
759 		UdpDomainSupport *domainSupport = it.Next();
760 		if (domainSupport->Domain() == domain)
761 			return domainSupport;
762 	}
763 
764 	if (!create)
765 		return NULL;
766 
767 	UdpDomainSupport *domainSupport =
768 		new (std::nothrow) UdpDomainSupport(domain);
769 	if (domainSupport == NULL || domainSupport->Init() < B_OK) {
770 		delete domainSupport;
771 		return NULL;
772 	}
773 
774 	fDomains.Add(domainSupport);
775 	return domainSupport;
776 }
777 
778 
779 // #pragma mark -
780 
781 
782 UdpEndpoint::UdpEndpoint(net_socket *socket)
783 	: DatagramSocket<>("udp endpoint", socket), fActive(false) {}
784 
785 
786 // #pragma mark - activation
787 
788 
789 status_t
790 UdpEndpoint::Bind(const sockaddr *address)
791 {
792 	TRACE_EP("Bind(%s)", AddressString(Domain(), address, true).Data());
793 	return fManager->BindEndpoint(this, address);
794 }
795 
796 
797 status_t
798 UdpEndpoint::Unbind(sockaddr *address)
799 {
800 	TRACE_EP("Unbind()");
801 	return fManager->UnbindEndpoint(this);
802 }
803 
804 
805 status_t
806 UdpEndpoint::Connect(const sockaddr *address)
807 {
808 	TRACE_EP("Connect(%s)", AddressString(Domain(), address, true).Data());
809 	return fManager->ConnectEndpoint(this, address);
810 }
811 
812 
813 status_t
814 UdpEndpoint::Open()
815 {
816 	TRACE_EP("Open()");
817 
818 	AutoLocker _(fLock);
819 
820 	status_t status = ProtocolSocket::Open();
821 	if (status < B_OK)
822 		return status;
823 
824 	fManager = sUdpEndpointManager->OpenEndpoint(this);
825 	if (fManager == NULL)
826 		return EAFNOSUPPORT;
827 
828 	return B_OK;
829 }
830 
831 
832 status_t
833 UdpEndpoint::Close()
834 {
835 	TRACE_EP("Close()");
836 	return B_OK;
837 }
838 
839 
840 status_t
841 UdpEndpoint::Free()
842 {
843 	TRACE_EP("Free()");
844 	fManager->UnbindEndpoint(this);
845 	return sUdpEndpointManager->FreeEndpoint(fManager);
846 }
847 
848 
849 // #pragma mark - outbound
850 
851 
852 status_t
853 UdpEndpoint::SendRoutedData(net_buffer *buffer, net_route *route)
854 {
855 	TRACE_EP("SendRoutedData(%p [%lu bytes], %p)", buffer, buffer->size, route);
856 
857 	if (buffer->size > (0xffff - sizeof(udp_header)))
858 		return EMSGSIZE;
859 
860 	buffer->protocol = IPPROTO_UDP;
861 
862 	// add and fill UDP-specific header:
863 	NetBufferPrepend<udp_header> header(buffer);
864 	if (header.Status() < B_OK)
865 		return header.Status();
866 
867 	header->source_port = AddressModule()->get_port(buffer->source);
868 	header->destination_port = AddressModule()->get_port(buffer->destination);
869 	header->udp_length = htons(buffer->size);
870 		// the udp-header is already included in the buffer-size
871 	header->udp_checksum = 0;
872 
873 	header.Sync();
874 
875 	uint16 calculatedChecksum = Checksum::PseudoHeader(AddressModule(),
876 		gBufferModule, buffer, IPPROTO_UDP);
877 	if (calculatedChecksum == 0)
878 		calculatedChecksum = 0xffff;
879 
880 	*UDPChecksumField(buffer) = calculatedChecksum;
881 
882 	TRACE_BLOCK(((char*)&header, sizeof(udp_header), "udp-hdr: "));
883 
884 	return next->module->send_routed_data(next, route, buffer);
885 }
886 
887 
888 status_t
889 UdpEndpoint::SendData(net_buffer *buffer)
890 {
891 	TRACE_EP("SendData(%p [%lu bytes])", buffer, buffer->size);
892 
893 	return gDatalinkModule->send_datagram(this, NULL, buffer);
894 }
895 
896 
897 // #pragma mark - inbound
898 
899 
900 ssize_t
901 UdpEndpoint::BytesAvailable()
902 {
903 	size_t bytes = AvailableData();
904 	TRACE_EP("BytesAvailable(): %lu", bytes);
905 	return bytes;
906 }
907 
908 
909 status_t
910 UdpEndpoint::FetchData(size_t numBytes, uint32 flags, net_buffer **_buffer)
911 {
912 	TRACE_EP("FetchData(%ld, 0x%lx)", numBytes, flags);
913 
914 	status_t status = SocketDequeue(flags, _buffer);
915 	TRACE_EP("  FetchData(): returned from fifo status=0x%lx", status);
916 	if (status < B_OK)
917 		return status;
918 
919 	TRACE_EP("  FetchData(): returns buffer with %ld bytes", (*_buffer)->size);
920 	return B_OK;
921 }
922 
923 
924 status_t
925 UdpEndpoint::StoreData(net_buffer *buffer)
926 {
927 	TRACE_EP("StoreData(%p [%ld bytes])", buffer, buffer->size);
928 
929 	return SocketEnqueue(buffer);
930 }
931 
932 
933 status_t
934 UdpEndpoint::DeliverData(net_buffer *_buffer)
935 {
936 	TRACE_EP("DeliverData(%p [%ld bytes])", _buffer, _buffer->size);
937 
938 	net_buffer *buffer = gBufferModule->clone(_buffer, false);
939 	if (buffer == NULL)
940 		return B_NO_MEMORY;
941 
942 	status_t status = sUdpEndpointManager->Deframe(buffer);
943 	if (status < B_OK) {
944 		gBufferModule->free(buffer);
945 		return status;
946 	}
947 
948 	// we call Enqueue() instead of SocketEnqueue() as there is
949 	// no need to clone the buffer again.
950 	return Enqueue(buffer);
951 }
952 
953 
954 // #pragma mark - protocol interface
955 
956 
957 net_protocol *
958 udp_init_protocol(net_socket *socket)
959 {
960 	socket->protocol = IPPROTO_UDP;
961 
962 	UdpEndpoint *endpoint = new (std::nothrow) UdpEndpoint(socket);
963 	if (endpoint == NULL || endpoint->InitCheck() < B_OK) {
964 		delete endpoint;
965 		return NULL;
966 	}
967 
968 	return endpoint;
969 }
970 
971 
972 status_t
973 udp_uninit_protocol(net_protocol *protocol)
974 {
975 	delete (UdpEndpoint *)protocol;
976 	return B_OK;
977 }
978 
979 
980 status_t
981 udp_open(net_protocol *protocol)
982 {
983 	return ((UdpEndpoint *)protocol)->Open();
984 }
985 
986 
987 status_t
988 udp_close(net_protocol *protocol)
989 {
990 	return ((UdpEndpoint *)protocol)->Close();
991 }
992 
993 
994 status_t
995 udp_free(net_protocol *protocol)
996 {
997 	return ((UdpEndpoint *)protocol)->Free();
998 }
999 
1000 
1001 status_t
1002 udp_connect(net_protocol *protocol, const struct sockaddr *address)
1003 {
1004 	return ((UdpEndpoint *)protocol)->Connect(address);
1005 }
1006 
1007 
1008 status_t
1009 udp_accept(net_protocol *protocol, struct net_socket **_acceptedSocket)
1010 {
1011 	return EOPNOTSUPP;
1012 }
1013 
1014 
1015 status_t
1016 udp_control(net_protocol *protocol, int level, int option, void *value,
1017 	size_t *_length)
1018 {
1019 	return protocol->next->module->control(protocol->next, level, option,
1020 		value, _length);
1021 }
1022 
1023 
1024 status_t
1025 udp_getsockopt(net_protocol *protocol, int level, int option, void *value,
1026 	int *length)
1027 {
1028 	return protocol->next->module->getsockopt(protocol->next, level, option,
1029 		value, length);
1030 }
1031 
1032 
1033 status_t
1034 udp_setsockopt(net_protocol *protocol, int level, int option,
1035 	const void *value, int length)
1036 {
1037 	return protocol->next->module->setsockopt(protocol->next, level, option,
1038 		value, length);
1039 }
1040 
1041 
1042 status_t
1043 udp_bind(net_protocol *protocol, const struct sockaddr *address)
1044 {
1045 	return ((UdpEndpoint *)protocol)->Bind(address);
1046 }
1047 
1048 
1049 status_t
1050 udp_unbind(net_protocol *protocol, struct sockaddr *address)
1051 {
1052 	return ((UdpEndpoint *)protocol)->Unbind(address);
1053 }
1054 
1055 
1056 status_t
1057 udp_listen(net_protocol *protocol, int count)
1058 {
1059 	return EOPNOTSUPP;
1060 }
1061 
1062 
1063 status_t
1064 udp_shutdown(net_protocol *protocol, int direction)
1065 {
1066 	return EOPNOTSUPP;
1067 }
1068 
1069 
1070 status_t
1071 udp_send_routed_data(net_protocol *protocol, struct net_route *route,
1072 	net_buffer *buffer)
1073 {
1074 	return ((UdpEndpoint *)protocol)->SendRoutedData(buffer, route);
1075 }
1076 
1077 
1078 status_t
1079 udp_send_data(net_protocol *protocol, net_buffer *buffer)
1080 {
1081 	return ((UdpEndpoint *)protocol)->SendData(buffer);
1082 }
1083 
1084 
1085 ssize_t
1086 udp_send_avail(net_protocol *protocol)
1087 {
1088 	return protocol->socket->send.buffer_size;
1089 }
1090 
1091 
1092 status_t
1093 udp_read_data(net_protocol *protocol, size_t numBytes, uint32 flags,
1094 	net_buffer **_buffer)
1095 {
1096 	return ((UdpEndpoint *)protocol)->FetchData(numBytes, flags, _buffer);
1097 }
1098 
1099 
1100 ssize_t
1101 udp_read_avail(net_protocol *protocol)
1102 {
1103 	return ((UdpEndpoint *)protocol)->BytesAvailable();
1104 }
1105 
1106 
1107 struct net_domain *
1108 udp_get_domain(net_protocol *protocol)
1109 {
1110 	return protocol->next->module->get_domain(protocol->next);
1111 }
1112 
1113 
1114 size_t
1115 udp_get_mtu(net_protocol *protocol, const struct sockaddr *address)
1116 {
1117 	return protocol->next->module->get_mtu(protocol->next, address);
1118 }
1119 
1120 
1121 status_t
1122 udp_receive_data(net_buffer *buffer)
1123 {
1124 	return sUdpEndpointManager->ReceiveData(buffer);
1125 }
1126 
1127 
1128 status_t
1129 udp_deliver_data(net_protocol *protocol, net_buffer *buffer)
1130 {
1131 	return ((UdpEndpoint *)protocol)->DeliverData(buffer);
1132 }
1133 
1134 
1135 status_t
1136 udp_error(uint32 code, net_buffer *data)
1137 {
1138 	return B_ERROR;
1139 }
1140 
1141 
1142 status_t
1143 udp_error_reply(net_protocol *protocol, net_buffer *causedError, uint32 code,
1144 	void *errorData)
1145 {
1146 	return B_ERROR;
1147 }
1148 
1149 
1150 //	#pragma mark - module interface
1151 
1152 
1153 static status_t
1154 init_udp()
1155 {
1156 	status_t status;
1157 	TRACE_EPM("init_udp()");
1158 
1159 	sUdpEndpointManager = new (std::nothrow) UdpEndpointManager;
1160 	if (sUdpEndpointManager == NULL)
1161 		return B_NO_MEMORY;
1162 
1163 	status = sUdpEndpointManager->InitCheck();
1164 	if (status != B_OK)
1165 		goto err1;
1166 
1167 	status = gStackModule->register_domain_protocols(AF_INET, SOCK_DGRAM, IPPROTO_IP,
1168 		"network/protocols/udp/v1",
1169 		"network/protocols/ipv4/v1",
1170 		NULL);
1171 	if (status < B_OK)
1172 		goto err1;
1173 	status = gStackModule->register_domain_protocols(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
1174 		"network/protocols/udp/v1",
1175 		"network/protocols/ipv4/v1",
1176 		NULL);
1177 	if (status < B_OK)
1178 		goto err1;
1179 
1180 	status = gStackModule->register_domain_receiving_protocol(AF_INET, IPPROTO_UDP,
1181 		"network/protocols/udp/v1");
1182 	if (status < B_OK)
1183 		goto err1;
1184 
1185 	add_debugger_command("udp_endpoints", UdpEndpointManager::DumpEndpoints,
1186 		"lists all open UDP endpoints");
1187 
1188 	return B_OK;
1189 
1190 err1:
1191 	delete sUdpEndpointManager;
1192 
1193 	TRACE_EPM("init_udp() fails with %lx (%s)", status, strerror(status));
1194 	return status;
1195 }
1196 
1197 
1198 static status_t
1199 uninit_udp()
1200 {
1201 	TRACE_EPM("uninit_udp()");
1202 	remove_debugger_command("udp_endpoints",
1203 		UdpEndpointManager::DumpEndpoints);
1204 	delete sUdpEndpointManager;
1205 	return B_OK;
1206 }
1207 
1208 
1209 static status_t
1210 udp_std_ops(int32 op, ...)
1211 {
1212 	switch (op) {
1213 		case B_MODULE_INIT:
1214 			return init_udp();
1215 
1216 		case B_MODULE_UNINIT:
1217 			return uninit_udp();
1218 
1219 		default:
1220 			return B_ERROR;
1221 	}
1222 }
1223 
1224 
1225 net_protocol_module_info sUDPModule = {
1226 	{
1227 		"network/protocols/udp/v1",
1228 		0,
1229 		udp_std_ops
1230 	},
1231 	NET_PROTOCOL_ATOMIC_MESSAGES,
1232 
1233 	udp_init_protocol,
1234 	udp_uninit_protocol,
1235 	udp_open,
1236 	udp_close,
1237 	udp_free,
1238 	udp_connect,
1239 	udp_accept,
1240 	udp_control,
1241 	udp_getsockopt,
1242 	udp_setsockopt,
1243 	udp_bind,
1244 	udp_unbind,
1245 	udp_listen,
1246 	udp_shutdown,
1247 	udp_send_data,
1248 	udp_send_routed_data,
1249 	udp_send_avail,
1250 	udp_read_data,
1251 	udp_read_avail,
1252 	udp_get_domain,
1253 	udp_get_mtu,
1254 	udp_receive_data,
1255 	udp_deliver_data,
1256 	udp_error,
1257 	udp_error_reply,
1258 };
1259 
1260 module_dependency module_dependencies[] = {
1261 	{NET_STACK_MODULE_NAME, (module_info **)&gStackModule},
1262 	{NET_BUFFER_MODULE_NAME, (module_info **)&gBufferModule},
1263 	{NET_DATALINK_MODULE_NAME, (module_info **)&gDatalinkModule},
1264 	{}
1265 };
1266 
1267 module_info *modules[] = {
1268 	(module_info *)&sUDPModule,
1269 	NULL
1270 };
1271