xref: /haiku/src/add-ons/kernel/network/stack/net_socket.cpp (revision 13581b3d2a71545960b98fefebc5225b5bf29072)
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  */
8 
9 
10 #include "stack_private.h"
11 
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/ioctl.h>
15 #include <sys/time.h>
16 
17 #include <new>
18 
19 #include <Drivers.h>
20 #include <KernelExport.h>
21 #include <Select.h>
22 
23 #include <AutoDeleter.h>
24 #include <team.h>
25 #include <util/AutoLock.h>
26 #include <util/list.h>
27 #include <WeakReferenceable.h>
28 
29 #include <fs/select_sync_pool.h>
30 #include <kernel.h>
31 
32 #include <net_protocol.h>
33 #include <net_stack.h>
34 #include <net_stat.h>
35 
36 #include "ancillary_data.h"
37 #include "utility.h"
38 
39 
40 //#define TRACE_SOCKET
41 #ifdef TRACE_SOCKET
42 #	define TRACE(x...) dprintf(STACK_DEBUG_PREFIX x)
43 #else
44 #	define TRACE(x...) ;
45 #endif
46 
47 
48 struct net_socket_private;
49 typedef DoublyLinkedList<net_socket_private> SocketList;
50 
51 struct net_socket_private : net_socket,
52 		DoublyLinkedListLinkImpl<net_socket_private>,
53 		BWeakReferenceable {
54 	net_socket_private();
55 	~net_socket_private();
56 
57 	void RemoveFromParent();
58 
59 	BWeakReference<net_socket_private> parent;
60 	team_id						owner;
61 	uint32						max_backlog;
62 	uint32						child_count;
63 	SocketList					pending_children;
64 	SocketList					connected_children;
65 
66 	struct select_sync_pool*	select_pool;
67 	mutex						lock;
68 
69 	bool						is_connected;
70 	bool						is_in_socket_list;
71 };
72 
73 
74 int socket_bind(net_socket* socket, const struct sockaddr* address,
75 	socklen_t addressLength);
76 int socket_setsockopt(net_socket* socket, int level, int option,
77 	const void* value, int length);
78 ssize_t socket_read_avail(net_socket* socket);
79 
80 static SocketList sSocketList;
81 static mutex sSocketLock;
82 
83 
84 net_socket_private::net_socket_private()
85 	:
86 	owner(-1),
87 	max_backlog(0),
88 	child_count(0),
89 	select_pool(NULL),
90 	is_connected(false),
91 	is_in_socket_list(false)
92 {
93 	first_protocol = NULL;
94 	first_info = NULL;
95 	options = 0;
96 	linger = 0;
97 	bound_to_device = 0;
98 	error = 0;
99 
100 	address.ss_len = 0;
101 	peer.ss_len = 0;
102 
103 	mutex_init(&lock, "socket");
104 
105 	// set defaults (may be overridden by the protocols)
106 	send.buffer_size = 65535;
107 	send.low_water_mark = 1;
108 	send.timeout = B_INFINITE_TIMEOUT;
109 	receive.buffer_size = 65535;
110 	receive.low_water_mark = 1;
111 	receive.timeout = B_INFINITE_TIMEOUT;
112 }
113 
114 
115 net_socket_private::~net_socket_private()
116 {
117 	TRACE("delete net_socket %p\n", this);
118 
119 	if (parent != NULL)
120 		panic("socket still has a parent!");
121 
122 	if (is_in_socket_list) {
123 		MutexLocker _(sSocketLock);
124 		sSocketList.Remove(this);
125 	}
126 
127 	mutex_lock(&lock);
128 
129 	// also delete all children of this socket
130 	while (net_socket_private* child = pending_children.RemoveHead()) {
131 		child->RemoveFromParent();
132 	}
133 	while (net_socket_private* child = connected_children.RemoveHead()) {
134 		child->RemoveFromParent();
135 	}
136 
137 	mutex_unlock(&lock);
138 
139 	put_domain_protocols(this);
140 
141 	mutex_destroy(&lock);
142 }
143 
144 
145 void
146 net_socket_private::RemoveFromParent()
147 {
148 	ASSERT(!is_in_socket_list && parent != NULL);
149 
150 	parent = NULL;
151 
152 	mutex_lock(&sSocketLock);
153 	sSocketList.Add(this);
154 	mutex_unlock(&sSocketLock);
155 
156 	is_in_socket_list = true;
157 
158 	ReleaseReference();
159 }
160 
161 
162 //	#pragma mark -
163 
164 
165 static status_t
166 create_socket(int family, int type, int protocol, net_socket_private** _socket)
167 {
168 	struct net_socket_private* socket = new(std::nothrow) net_socket_private;
169 	if (socket == NULL)
170 		return B_NO_MEMORY;
171 	status_t status = socket->InitCheck();
172 	if (status != B_OK) {
173 		delete socket;
174 		return status;
175 	}
176 
177 	socket->family = family;
178 	socket->type = type;
179 	socket->protocol = protocol;
180 
181 	status = get_domain_protocols(socket);
182 	if (status != B_OK) {
183 		delete socket;
184 		return status;
185 	}
186 
187 	TRACE("create net_socket %p (%u.%u.%u):\n", socket, socket->family,
188 		socket->type, socket->protocol);
189 
190 #ifdef TRACE_SOCKET
191 	net_protocol* current = socket->first_protocol;
192 	for (int i = 0; current != NULL; current = current->next, i++)
193 		TRACE("  [%d] %p  %s\n", i, current, current->module->info.name);
194 #endif
195 
196 	*_socket = socket;
197 	return B_OK;
198 }
199 
200 
201 static status_t
202 add_ancillary_data(net_socket* socket, ancillary_data_container* container,
203 	void* data, size_t dataLen)
204 {
205 	cmsghdr* header = (cmsghdr*)data;
206 
207 	if (dataLen == 0)
208 		return B_OK;
209 
210 	if (socket->first_info->add_ancillary_data == NULL)
211 		return B_NOT_SUPPORTED;
212 
213 	while (true) {
214 		if (header->cmsg_len < CMSG_LEN(0) || header->cmsg_len > dataLen)
215 			return B_BAD_VALUE;
216 
217 		status_t status = socket->first_info->add_ancillary_data(
218 			socket->first_protocol, container, header);
219 		if (status != B_OK)
220 			return status;
221 
222 		if (dataLen <= _ALIGN(header->cmsg_len))
223 			break;
224 		dataLen -= _ALIGN(header->cmsg_len);
225 		header = (cmsghdr*)((uint8*)header + _ALIGN(header->cmsg_len));
226 	}
227 
228 	return B_OK;
229 }
230 
231 
232 static status_t
233 process_ancillary_data(net_socket* socket, ancillary_data_container* container,
234 	msghdr* messageHeader)
235 {
236 	uint8* dataBuffer = (uint8*)messageHeader->msg_control;
237 	int dataBufferLen = messageHeader->msg_controllen;
238 
239 	if (container == NULL || dataBuffer == NULL) {
240 		messageHeader->msg_controllen = 0;
241 		return B_OK;
242 	}
243 
244 	ancillary_data_header header;
245 	void* data = NULL;
246 
247 	while ((data = next_ancillary_data(container, data, &header)) != NULL) {
248 		if (socket->first_info->process_ancillary_data == NULL)
249 			return B_NOT_SUPPORTED;
250 
251 		ssize_t bytesWritten = socket->first_info->process_ancillary_data(
252 			socket->first_protocol, &header, data, dataBuffer, dataBufferLen);
253 		if (bytesWritten < 0)
254 			return bytesWritten;
255 
256 		dataBuffer += bytesWritten;
257 		dataBufferLen -= bytesWritten;
258 	}
259 
260 	messageHeader->msg_controllen -= dataBufferLen;
261 
262 	return B_OK;
263 }
264 
265 
266 static status_t
267 process_ancillary_data(net_socket* socket,
268 	net_buffer* buffer, msghdr* messageHeader)
269 {
270 	void *dataBuffer = messageHeader->msg_control;
271 	ssize_t bytesWritten;
272 
273 	if (dataBuffer == NULL) {
274 		messageHeader->msg_controllen = 0;
275 		return B_OK;
276 	}
277 
278 	if (socket->first_info->process_ancillary_data_no_container == NULL)
279 		return B_NOT_SUPPORTED;
280 
281 	bytesWritten = socket->first_info->process_ancillary_data_no_container(
282 		socket->first_protocol, buffer, dataBuffer,
283 		messageHeader->msg_controllen);
284 	if (bytesWritten < 0)
285 		return bytesWritten;
286 	messageHeader->msg_controllen = bytesWritten;
287 
288 	return B_OK;
289 }
290 
291 
292 static ssize_t
293 socket_receive_no_buffer(net_socket* socket, msghdr* header, void* data,
294 	size_t length, int flags)
295 {
296 	iovec stackVec = { data, length };
297 	iovec* vecs = header ? header->msg_iov : &stackVec;
298 	int vecCount = header ? header->msg_iovlen : 1;
299 	sockaddr* address = header ? (sockaddr*)header->msg_name : NULL;
300 	socklen_t* addressLen = header ? &header->msg_namelen : NULL;
301 
302 	ancillary_data_container* ancillaryData = NULL;
303 	ssize_t bytesRead = socket->first_info->read_data_no_buffer(
304 		socket->first_protocol, vecs, vecCount, &ancillaryData, address,
305 		addressLen, flags);
306 	if (bytesRead < 0)
307 		return bytesRead;
308 
309 	CObjectDeleter<
310 		ancillary_data_container, void, delete_ancillary_data_container>
311 		ancillaryDataDeleter(ancillaryData);
312 
313 	// process ancillary data
314 	if (header != NULL) {
315 		status_t status = process_ancillary_data(socket, ancillaryData, header);
316 		if (status != B_OK)
317 			return status;
318 
319 		header->msg_flags = 0;
320 	}
321 
322 	return bytesRead;
323 }
324 
325 
326 #if ENABLE_DEBUGGER_COMMANDS
327 
328 
329 static void
330 print_socket_line(net_socket_private* socket, const char* prefix)
331 {
332 	BReference<net_socket_private> parent = socket->parent.GetReference();
333 	kprintf("%s%p %2d.%2d.%2d %6" B_PRId32 " %p %p  %p%s\n", prefix, socket,
334 		socket->family, socket->type, socket->protocol, socket->owner,
335 		socket->first_protocol, socket->first_info, parent.Get(),
336 		parent.IsSet() ? socket->is_connected ? " (c)" : " (p)" : "");
337 }
338 
339 
340 static int
341 dump_socket(int argc, char** argv)
342 {
343 	if (argc < 2) {
344 		kprintf("usage: %s [address]\n", argv[0]);
345 		return 0;
346 	}
347 
348 	net_socket_private* socket = (net_socket_private*)parse_expression(argv[1]);
349 
350 	kprintf("SOCKET %p\n", socket);
351 	kprintf("  family.type.protocol: %d.%d.%d\n",
352 		socket->family, socket->type, socket->protocol);
353 	BReference<net_socket_private> parent = socket->parent.GetReference();
354 	kprintf("  parent:               %p\n", parent.Get());
355 	kprintf("  first protocol:       %p\n", socket->first_protocol);
356 	kprintf("  first module_info:    %p\n", socket->first_info);
357 	kprintf("  options:              %x\n", socket->options);
358 	kprintf("  linger:               %d\n", socket->linger);
359 	kprintf("  bound to device:      %" B_PRIu32 "\n", socket->bound_to_device);
360 	kprintf("  owner:                %" B_PRId32 "\n", socket->owner);
361 	kprintf("  max backlog:          %" B_PRId32 "\n", socket->max_backlog);
362 	kprintf("  is connected:         %d\n", socket->is_connected);
363 	kprintf("  child_count:          %" B_PRIu32 "\n", socket->child_count);
364 
365 	if (socket->child_count == 0)
366 		return 0;
367 
368 	kprintf("    pending children:\n");
369 	SocketList::Iterator iterator = socket->pending_children.GetIterator();
370 	while (net_socket_private* child = iterator.Next()) {
371 		print_socket_line(child, "      ");
372 	}
373 
374 	kprintf("    connected children:\n");
375 	iterator = socket->connected_children.GetIterator();
376 	while (net_socket_private* child = iterator.Next()) {
377 		print_socket_line(child, "      ");
378 	}
379 
380 	return 0;
381 }
382 
383 
384 static int
385 dump_sockets(int argc, char** argv)
386 {
387 	kprintf("address        kind  owner protocol   module_info parent\n");
388 
389 	SocketList::Iterator iterator = sSocketList.GetIterator();
390 	while (net_socket_private* socket = iterator.Next()) {
391 		print_socket_line(socket, "");
392 
393 		SocketList::Iterator childIterator
394 			= socket->pending_children.GetIterator();
395 		while (net_socket_private* child = childIterator.Next()) {
396 			print_socket_line(child, " ");
397 		}
398 
399 		childIterator = socket->connected_children.GetIterator();
400 		while (net_socket_private* child = childIterator.Next()) {
401 			print_socket_line(child, " ");
402 		}
403 	}
404 
405 	return 0;
406 }
407 
408 
409 #endif	// ENABLE_DEBUGGER_COMMANDS
410 
411 
412 //	#pragma mark -
413 
414 
415 status_t
416 socket_open(int family, int type, int protocol, net_socket** _socket)
417 {
418 	net_socket_private* socket;
419 	status_t status = create_socket(family, type, protocol, &socket);
420 	if (status != B_OK)
421 		return status;
422 
423 	status = socket->first_info->open(socket->first_protocol);
424 	if (status != B_OK) {
425 		delete socket;
426 		return status;
427 	}
428 
429 	socket->owner = team_get_current_team_id();
430 	socket->is_in_socket_list = true;
431 
432 	mutex_lock(&sSocketLock);
433 	sSocketList.Add(socket);
434 	mutex_unlock(&sSocketLock);
435 
436 	*_socket = socket;
437 	return B_OK;
438 }
439 
440 
441 status_t
442 socket_close(net_socket* _socket)
443 {
444 	net_socket_private* socket = (net_socket_private*)_socket;
445 	return socket->first_info->close(socket->first_protocol);
446 }
447 
448 
449 void
450 socket_free(net_socket* _socket)
451 {
452 	net_socket_private* socket = (net_socket_private*)_socket;
453 	socket->first_info->free(socket->first_protocol);
454 	socket->ReleaseReference();
455 }
456 
457 
458 status_t
459 socket_control(net_socket* socket, uint32 op, void* data, size_t length)
460 {
461 	switch (op) {
462 		case FIONREAD:
463 		{
464 			if (data == NULL || (socket->options & SO_ACCEPTCONN) != 0)
465 				return B_BAD_VALUE;
466 
467 			int available = (int)socket_read_avail(socket);
468 			if (available < 0)
469 				available = 0;
470 
471 			if (is_syscall()) {
472 				if (!IS_USER_ADDRESS(data)
473 					|| user_memcpy(data, &available, sizeof(available))
474 						!= B_OK) {
475 					return B_BAD_ADDRESS;
476 				}
477 			} else
478 				*(int*)data = available;
479 
480 			return B_OK;
481 		}
482 
483 		case B_SET_BLOCKING_IO:
484 		case B_SET_NONBLOCKING_IO:
485 		{
486 			int value = op == B_SET_NONBLOCKING_IO;
487 			return socket_setsockopt(socket, SOL_SOCKET, SO_NONBLOCK, &value,
488 				sizeof(int));
489 		}
490 	}
491 
492 	return socket->first_info->control(socket->first_protocol,
493 		LEVEL_DRIVER_IOCTL, op, data, &length);
494 }
495 
496 
497 ssize_t
498 socket_read_avail(net_socket* socket)
499 {
500 	return socket->first_info->read_avail(socket->first_protocol);
501 }
502 
503 
504 ssize_t
505 socket_send_avail(net_socket* socket)
506 {
507 	return socket->first_info->send_avail(socket->first_protocol);
508 }
509 
510 
511 status_t
512 socket_send_data(net_socket* socket, net_buffer* buffer)
513 {
514 	return socket->first_info->send_data(socket->first_protocol,
515 		buffer);
516 }
517 
518 
519 status_t
520 socket_receive_data(net_socket* socket, size_t length, uint32 flags,
521 	net_buffer** _buffer)
522 {
523 	status_t status = socket->first_info->read_data(socket->first_protocol,
524 		length, flags, _buffer);
525 	if (status != B_OK)
526 		return status;
527 
528 	if (*_buffer && length < (*_buffer)->size) {
529 		// discard any data behind the amount requested
530 		gNetBufferModule.trim(*_buffer, length);
531 	}
532 
533 	return status;
534 }
535 
536 
537 status_t
538 socket_get_next_stat(uint32* _cookie, int family, struct net_stat* stat)
539 {
540 	MutexLocker locker(sSocketLock);
541 
542 	net_socket_private* socket = NULL;
543 	SocketList::Iterator iterator = sSocketList.GetIterator();
544 	uint32 cookie = *_cookie;
545 	uint32 count = 0;
546 
547 	while (true) {
548 		socket = iterator.Next();
549 		if (socket == NULL)
550 			return B_ENTRY_NOT_FOUND;
551 
552 		// TODO: also traverse the pending connections
553 		if (count == cookie)
554 			break;
555 
556 		if (family == -1 || family == socket->family)
557 			count++;
558 	}
559 
560 	*_cookie = count + 1;
561 
562 	stat->family = socket->family;
563 	stat->type = socket->type;
564 	stat->protocol = socket->protocol;
565 	stat->owner = socket->owner;
566 	stat->state[0] = '\0';
567 	memcpy(&stat->address, &socket->address, sizeof(struct sockaddr_storage));
568 	memcpy(&stat->peer, &socket->peer, sizeof(struct sockaddr_storage));
569 	stat->receive_queue_size = 0;
570 	stat->send_queue_size = 0;
571 
572 	// fill in protocol specific data (if supported by the protocol)
573 	size_t length = sizeof(net_stat);
574 	socket->first_info->control(socket->first_protocol, socket->protocol,
575 		NET_STAT_SOCKET, stat, &length);
576 
577 	return B_OK;
578 }
579 
580 
581 //	#pragma mark - connections
582 
583 
584 bool
585 socket_acquire(net_socket* _socket)
586 {
587 	net_socket_private* socket = (net_socket_private*)_socket;
588 
589 	// During destruction, the socket might still be accessible over its
590 	// endpoint protocol. We need to make sure the endpoint cannot acquire the
591 	// socket anymore -- while not obvious, the endpoint protocol is responsible
592 	// for the proper locking here.
593 	if (socket->CountReferences() == 0)
594 		return false;
595 
596 	socket->AcquireReference();
597 	return true;
598 }
599 
600 
601 bool
602 socket_release(net_socket* _socket)
603 {
604 	net_socket_private* socket = (net_socket_private*)_socket;
605 	return socket->ReleaseReference();
606 }
607 
608 
609 status_t
610 socket_spawn_pending(net_socket* _parent, net_socket** _socket)
611 {
612 	net_socket_private* parent = (net_socket_private*)_parent;
613 
614 	TRACE("%s(%p)\n", __FUNCTION__, parent);
615 
616 	MutexLocker locker(parent->lock);
617 
618 	// We actually accept more pending connections to compensate for those
619 	// that never complete, and also make sure at least a single connection
620 	// can always be accepted
621 	if (parent->child_count > 3 * parent->max_backlog / 2)
622 		return ENOBUFS;
623 
624 	net_socket_private* socket;
625 	status_t status = create_socket(parent->family, parent->type,
626 		parent->protocol, &socket);
627 	if (status != B_OK)
628 		return status;
629 
630 	// inherit parent's properties
631 	socket->send = parent->send;
632 	socket->receive = parent->receive;
633 	socket->options = parent->options & (SO_KEEPALIVE | SO_DONTROUTE | SO_LINGER | SO_OOBINLINE);
634 	socket->linger = parent->linger;
635 	socket->owner = parent->owner;
636 	memcpy(&socket->address, &parent->address, parent->address.ss_len);
637 	memcpy(&socket->peer, &parent->peer, parent->peer.ss_len);
638 
639 	// add to the parent's list of pending connections
640 	parent->pending_children.Add(socket);
641 	socket->parent = parent;
642 	parent->child_count++;
643 
644 	*_socket = socket;
645 	return B_OK;
646 }
647 
648 
649 /*!	Dequeues a connected child from a parent socket.
650 	It also returns a reference with the child socket.
651 */
652 status_t
653 socket_dequeue_connected(net_socket* _parent, net_socket** _socket)
654 {
655 	net_socket_private* parent = (net_socket_private*)_parent;
656 
657 	mutex_lock(&parent->lock);
658 
659 	net_socket_private* socket = parent->connected_children.RemoveHead();
660 	if (socket != NULL) {
661 		socket->AcquireReference();
662 		socket->RemoveFromParent();
663 		parent->child_count--;
664 		*_socket = socket;
665 	}
666 
667 	mutex_unlock(&parent->lock);
668 
669 	if (socket == NULL)
670 		return B_ENTRY_NOT_FOUND;
671 
672 	return B_OK;
673 }
674 
675 
676 ssize_t
677 socket_count_connected(net_socket* _parent)
678 {
679 	net_socket_private* parent = (net_socket_private*)_parent;
680 
681 	MutexLocker _(parent->lock);
682 	return parent->connected_children.Count();
683 }
684 
685 
686 status_t
687 socket_set_max_backlog(net_socket* _socket, uint32 backlog)
688 {
689 	net_socket_private* socket = (net_socket_private*)_socket;
690 
691 	// we enforce an upper limit of connections waiting to be accepted
692 	if (backlog > 256)
693 		backlog = 256;
694 
695 	MutexLocker _(socket->lock);
696 
697 	// first remove the pending connections, then the already connected
698 	// ones as needed
699 	net_socket_private* child;
700 	while (socket->child_count > backlog
701 		&& (child = socket->pending_children.RemoveTail()) != NULL) {
702 		child->RemoveFromParent();
703 		socket->child_count--;
704 	}
705 	while (socket->child_count > backlog
706 		&& (child = socket->connected_children.RemoveTail()) != NULL) {
707 		child->RemoveFromParent();
708 		socket->child_count--;
709 	}
710 
711 	socket->max_backlog = backlog;
712 	return B_OK;
713 }
714 
715 
716 /*!	Returns whether or not this socket has a parent. The parent might not be
717 	valid anymore, though.
718 */
719 bool
720 socket_has_parent(net_socket* _socket)
721 {
722 	net_socket_private* socket = (net_socket_private*)_socket;
723 	return socket->parent != NULL;
724 }
725 
726 
727 /*!	The socket has been connected. It will be moved to the connected queue
728 	of its parent socket.
729 */
730 status_t
731 socket_connected(net_socket* _socket)
732 {
733 	net_socket_private* socket = (net_socket_private*)_socket;
734 
735 	TRACE("socket_connected(%p)\n", socket);
736 
737 	if (socket->parent == NULL) {
738 		socket->is_connected = true;
739 		return B_OK;
740 	}
741 
742 	BReference<net_socket_private> parent = socket->parent.GetReference();
743 	if (!parent.IsSet())
744 		return B_BAD_VALUE;
745 
746 	MutexLocker _(parent->lock);
747 
748 	parent->pending_children.Remove(socket);
749 	parent->connected_children.Add(socket);
750 	socket->is_connected = true;
751 
752 	// notify parent
753 	if (parent->select_pool)
754 		notify_select_event_pool(parent->select_pool, B_SELECT_READ);
755 
756 	return B_OK;
757 }
758 
759 
760 /*!	The socket has been aborted. Steals the parent's reference, and releases
761 	it.
762 */
763 status_t
764 socket_aborted(net_socket* _socket)
765 {
766 	net_socket_private* socket = (net_socket_private*)_socket;
767 
768 	TRACE("socket_aborted(%p)\n", socket);
769 
770 	BReference<net_socket_private> parent = socket->parent.GetReference();
771 	if (!parent.IsSet())
772 		return B_BAD_VALUE;
773 
774 	MutexLocker _(parent->lock);
775 
776 	if (socket->is_connected)
777 		parent->connected_children.Remove(socket);
778 	else
779 		parent->pending_children.Remove(socket);
780 
781 	parent->child_count--;
782 	socket->RemoveFromParent();
783 
784 	return B_OK;
785 }
786 
787 
788 //	#pragma mark - notifications
789 
790 
791 status_t
792 socket_request_notification(net_socket* _socket, uint8 event, selectsync* sync)
793 {
794 	net_socket_private* socket = (net_socket_private*)_socket;
795 
796 	mutex_lock(&socket->lock);
797 
798 	status_t status = add_select_sync_pool_entry(&socket->select_pool, sync,
799 		event);
800 
801 	mutex_unlock(&socket->lock);
802 
803 	if (status != B_OK)
804 		return status;
805 
806 	// check if the event is already present
807 	// TODO: add support for poll() types
808 
809 	switch (event) {
810 		case B_SELECT_READ:
811 		{
812 			ssize_t available = socket_read_avail(socket);
813 			if ((ssize_t)socket->receive.low_water_mark <= available
814 				|| available < B_OK)
815 				notify_select_event(sync, event);
816 			break;
817 		}
818 		case B_SELECT_WRITE:
819 		{
820 			if ((socket->options & SO_ACCEPTCONN) != 0)
821 				break;
822 
823 			ssize_t available = socket_send_avail(socket);
824 			if ((ssize_t)socket->send.low_water_mark <= available
825 				|| available < B_OK)
826 				notify_select_event(sync, event);
827 			break;
828 		}
829 		case B_SELECT_ERROR:
830 			if (socket->error != B_OK)
831 				notify_select_event(sync, event);
832 			break;
833 	}
834 
835 	return B_OK;
836 }
837 
838 
839 status_t
840 socket_cancel_notification(net_socket* _socket, uint8 event, selectsync* sync)
841 {
842 	net_socket_private* socket = (net_socket_private*)_socket;
843 
844 	MutexLocker _(socket->lock);
845 	return remove_select_sync_pool_entry(&socket->select_pool, sync, event);
846 }
847 
848 
849 status_t
850 socket_notify(net_socket* _socket, uint8 event, int32 value)
851 {
852 	net_socket_private* socket = (net_socket_private*)_socket;
853 	bool notify = true;
854 
855 	switch (event) {
856 		case B_SELECT_READ:
857 			if ((ssize_t)socket->receive.low_water_mark > value
858 				&& value >= B_OK)
859 				notify = false;
860 			break;
861 
862 		case B_SELECT_WRITE:
863 			if ((ssize_t)socket->send.low_water_mark > value && value >= B_OK)
864 				notify = false;
865 			break;
866 
867 		case B_SELECT_ERROR:
868 			socket->error = value;
869 			break;
870 	}
871 
872 	MutexLocker _(socket->lock);
873 
874 	if (notify && socket->select_pool != NULL) {
875 		notify_select_event_pool(socket->select_pool, event);
876 
877 		if (event == B_SELECT_ERROR) {
878 			// always notify read/write on error
879 			notify_select_event_pool(socket->select_pool, B_SELECT_READ);
880 			notify_select_event_pool(socket->select_pool, B_SELECT_WRITE);
881 		}
882 	}
883 
884 	return B_OK;
885 }
886 
887 
888 //	#pragma mark - standard socket API
889 
890 
891 int
892 socket_accept(net_socket* socket, struct sockaddr* address,
893 	socklen_t* _addressLength, net_socket** _acceptedSocket)
894 {
895 	if ((socket->options & SO_ACCEPTCONN) == 0)
896 		return B_BAD_VALUE;
897 
898 	net_socket* accepted;
899 	status_t status = socket->first_info->accept(socket->first_protocol,
900 		&accepted);
901 	if (status != B_OK)
902 		return status;
903 
904 	if (address && *_addressLength > 0) {
905 		memcpy(address, &accepted->peer, min_c(*_addressLength,
906 			min_c(accepted->peer.ss_len, sizeof(sockaddr_storage))));
907 		*_addressLength = accepted->peer.ss_len;
908 	}
909 
910 	*_acceptedSocket = accepted;
911 	return B_OK;
912 }
913 
914 
915 int
916 socket_bind(net_socket* socket, const struct sockaddr* address,
917 	socklen_t addressLength)
918 {
919 	sockaddr empty;
920 	if (address == NULL) {
921 		// special - try to bind to an empty address, like INADDR_ANY
922 		memset(&empty, 0, sizeof(sockaddr));
923 		empty.sa_len = sizeof(sockaddr);
924 		empty.sa_family = socket->family;
925 
926 		address = &empty;
927 		addressLength = sizeof(sockaddr);
928 	}
929 
930 	if (socket->address.ss_len != 0)
931 		return B_BAD_VALUE;
932 
933 	memcpy(&socket->address, address, sizeof(sockaddr));
934 	socket->address.ss_len = sizeof(sockaddr_storage);
935 
936 	status_t status = socket->first_info->bind(socket->first_protocol,
937 		(sockaddr*)address);
938 	if (status != B_OK) {
939 		// clear address again, as binding failed
940 		socket->address.ss_len = 0;
941 	}
942 
943 	return status;
944 }
945 
946 
947 int
948 socket_connect(net_socket* socket, const struct sockaddr* address,
949 	socklen_t addressLength)
950 {
951 	if (address == NULL || addressLength == 0)
952 		return ENETUNREACH;
953 
954 	if (socket->address.ss_len == 0) {
955 		// try to bind first
956 		status_t status = socket_bind(socket, NULL, 0);
957 		if (status != B_OK)
958 			return status;
959 	}
960 
961 	return socket->first_info->connect(socket->first_protocol, address);
962 }
963 
964 
965 int
966 socket_getpeername(net_socket* _socket, struct sockaddr* address,
967 	socklen_t* _addressLength)
968 {
969 	net_socket_private* socket = (net_socket_private*)_socket;
970 	BReference<net_socket_private> parent = socket->parent.GetReference();
971 
972 	if ((!parent.IsSet() && !socket->is_connected) || socket->peer.ss_len == 0)
973 		return ENOTCONN;
974 
975 	memcpy(address, &socket->peer, min_c(*_addressLength, socket->peer.ss_len));
976 	*_addressLength = socket->peer.ss_len;
977 	return B_OK;
978 }
979 
980 
981 int
982 socket_getsockname(net_socket* socket, struct sockaddr* address,
983 	socklen_t* _addressLength)
984 {
985 	if (socket->address.ss_len == 0) {
986 		struct sockaddr buffer;
987 		memset(&buffer, 0, sizeof(buffer));
988 		buffer.sa_family = socket->family;
989 
990 		memcpy(address, &buffer, min_c(*_addressLength, sizeof(buffer)));
991 		*_addressLength = sizeof(buffer);
992 		return B_OK;
993 	}
994 
995 	memcpy(address, &socket->address, min_c(*_addressLength,
996 		socket->address.ss_len));
997 	*_addressLength = socket->address.ss_len;
998 	return B_OK;
999 }
1000 
1001 
1002 status_t
1003 socket_get_option(net_socket* socket, int level, int option, void* value,
1004 	int* _length)
1005 {
1006 	if (level != SOL_SOCKET)
1007 		return ENOPROTOOPT;
1008 
1009 	switch (option) {
1010 		case SO_SNDBUF:
1011 		{
1012 			uint32* size = (uint32*)value;
1013 			*size = socket->send.buffer_size;
1014 			*_length = sizeof(uint32);
1015 			return B_OK;
1016 		}
1017 
1018 		case SO_RCVBUF:
1019 		{
1020 			uint32* size = (uint32*)value;
1021 			*size = socket->receive.buffer_size;
1022 			*_length = sizeof(uint32);
1023 			return B_OK;
1024 		}
1025 
1026 		case SO_SNDLOWAT:
1027 		{
1028 			uint32* size = (uint32*)value;
1029 			*size = socket->send.low_water_mark;
1030 			*_length = sizeof(uint32);
1031 			return B_OK;
1032 		}
1033 
1034 		case SO_RCVLOWAT:
1035 		{
1036 			uint32* size = (uint32*)value;
1037 			*size = socket->receive.low_water_mark;
1038 			*_length = sizeof(uint32);
1039 			return B_OK;
1040 		}
1041 
1042 		case SO_RCVTIMEO:
1043 		case SO_SNDTIMEO:
1044 		{
1045 			if (*_length < (int)sizeof(struct timeval))
1046 				return B_BAD_VALUE;
1047 
1048 			bigtime_t timeout;
1049 			if (option == SO_SNDTIMEO)
1050 				timeout = socket->send.timeout;
1051 			else
1052 				timeout = socket->receive.timeout;
1053 			if (timeout == B_INFINITE_TIMEOUT)
1054 				timeout = 0;
1055 
1056 			struct timeval* timeval = (struct timeval*)value;
1057 			timeval->tv_sec = timeout / 1000000LL;
1058 			timeval->tv_usec = timeout % 1000000LL;
1059 
1060 			*_length = sizeof(struct timeval);
1061 			return B_OK;
1062 		}
1063 
1064 		case SO_NONBLOCK:
1065 		{
1066 			int32* _set = (int32*)value;
1067 			*_set = socket->receive.timeout == 0 && socket->send.timeout == 0;
1068 			*_length = sizeof(int32);
1069 			return B_OK;
1070 		}
1071 
1072 		case SO_ACCEPTCONN:
1073 		case SO_BROADCAST:
1074 		case SO_DEBUG:
1075 		case SO_DONTROUTE:
1076 		case SO_KEEPALIVE:
1077 		case SO_OOBINLINE:
1078 		case SO_REUSEADDR:
1079 		case SO_REUSEPORT:
1080 		case SO_USELOOPBACK:
1081 		{
1082 			int32* _set = (int32*)value;
1083 			*_set = (socket->options & option) != 0;
1084 			*_length = sizeof(int32);
1085 			return B_OK;
1086 		}
1087 
1088 		case SO_TYPE:
1089 		{
1090 			int32* _set = (int32*)value;
1091 			*_set = socket->type;
1092 			*_length = sizeof(int32);
1093 			return B_OK;
1094 		}
1095 
1096 		case SO_ERROR:
1097 		{
1098 			int32* _set = (int32*)value;
1099 			*_set = socket->error;
1100 			*_length = sizeof(int32);
1101 
1102 			socket->error = B_OK;
1103 				// clear error upon retrieval
1104 			return B_OK;
1105 		}
1106 
1107 		default:
1108 			break;
1109 	}
1110 
1111 	dprintf("socket_getsockopt: unknown option %d\n", option);
1112 	return ENOPROTOOPT;
1113 }
1114 
1115 
1116 int
1117 socket_getsockopt(net_socket* socket, int level, int option, void* value,
1118 	int* _length)
1119 {
1120 	return socket->first_protocol->module->getsockopt(socket->first_protocol,
1121 		level, option, value, _length);
1122 }
1123 
1124 
1125 int
1126 socket_listen(net_socket* socket, int backlog)
1127 {
1128 	status_t status = socket->first_info->listen(socket->first_protocol,
1129 		backlog);
1130 	if (status == B_OK)
1131 		socket->options |= SO_ACCEPTCONN;
1132 
1133 	return status;
1134 }
1135 
1136 
1137 ssize_t
1138 socket_receive(net_socket* socket, msghdr* header, void* data, size_t length,
1139 	int flags)
1140 {
1141 	const int originalFlags = flags;
1142 
1143 	// MSG_NOSIGNAL is only meaningful for send(), not receive(), but it is
1144 	// sometimes specified anyway. Mask it off to avoid unnecessary errors.
1145 	flags &= ~MSG_NOSIGNAL;
1146 
1147 	// If the protocol sports read_data_no_buffer() we use it.
1148 	if (socket->first_info->read_data_no_buffer != NULL)
1149 		return socket_receive_no_buffer(socket, header, data, length, flags);
1150 
1151 	// Mask off flags handled in this function.
1152 	flags &= ~(MSG_TRUNC);
1153 
1154 	size_t totalLength = length;
1155 	if (header != NULL) {
1156 		ASSERT(data == header->msg_iov[0].iov_base);
1157 
1158 		// calculate the length considering all of the extra buffers
1159 		for (int i = 1; i < header->msg_iovlen; i++)
1160 			totalLength += header->msg_iov[i].iov_len;
1161 	}
1162 
1163 	net_buffer* buffer;
1164 	status_t status = socket->first_info->read_data(
1165 		socket->first_protocol, totalLength, flags, &buffer);
1166 	if (status != B_OK)
1167 		return status;
1168 
1169 	// process ancillary data
1170 	if (header != NULL) {
1171 		if (buffer != NULL && header->msg_control != NULL) {
1172 			ancillary_data_container* container
1173 				= gNetBufferModule.get_ancillary_data(buffer);
1174 			if (container != NULL)
1175 				status = process_ancillary_data(socket, container, header);
1176 			else
1177 				status = process_ancillary_data(socket, buffer, header);
1178 			if (status != B_OK) {
1179 				gNetBufferModule.free(buffer);
1180 				return status;
1181 			}
1182 		} else
1183 			header->msg_controllen = 0;
1184 	}
1185 
1186 	// TODO: - returning a NULL buffer when received 0 bytes
1187 	//         may not make much sense as we still need the address
1188 
1189 	size_t nameLen = 0;
1190 	if (header != NULL) {
1191 		// TODO: - consider the control buffer options
1192 		nameLen = header->msg_namelen;
1193 		header->msg_namelen = 0;
1194 		header->msg_flags = 0;
1195 	}
1196 
1197 	if (buffer == NULL)
1198 		return 0;
1199 
1200 	const size_t bytesReceived = buffer->size;
1201 	size_t bytesCopied = 0;
1202 
1203 	size_t toRead = min_c(bytesReceived, length);
1204 	status = gNetBufferModule.read(buffer, 0, data, toRead);
1205 	if (status != B_OK) {
1206 		gNetBufferModule.free(buffer);
1207 
1208 		if (status == B_BAD_ADDRESS)
1209 			return status;
1210 		return ENOBUFS;
1211 	}
1212 
1213 	// if first copy was a success, proceed to following copies as required
1214 	bytesCopied += toRead;
1215 
1216 	if (header != NULL) {
1217 		// We start at iovec[1] as { data, length } is iovec[0].
1218 		for (int i = 1; i < header->msg_iovlen && bytesCopied < bytesReceived; i++) {
1219 			iovec& vec = header->msg_iov[i];
1220 			toRead = min_c(bytesReceived - bytesCopied, vec.iov_len);
1221 			if (gNetBufferModule.read(buffer, bytesCopied, vec.iov_base,
1222 					toRead) < B_OK) {
1223 				break;
1224 			}
1225 
1226 			bytesCopied += toRead;
1227 		}
1228 
1229 		if (header->msg_name != NULL) {
1230 			header->msg_namelen = min_c(nameLen, buffer->source->sa_len);
1231 			memcpy(header->msg_name, buffer->source, header->msg_namelen);
1232 		}
1233 	}
1234 
1235 	gNetBufferModule.free(buffer);
1236 
1237 	if (bytesCopied < bytesReceived) {
1238 		if (header != NULL)
1239 			header->msg_flags = MSG_TRUNC;
1240 
1241 		if ((originalFlags & MSG_TRUNC) != 0)
1242 			return bytesReceived;
1243 	}
1244 
1245 	return bytesCopied;
1246 }
1247 
1248 
1249 ssize_t
1250 socket_send(net_socket* socket, msghdr* header, const void* data, size_t length,
1251 	int flags)
1252 {
1253 	const bool nosignal = ((flags & MSG_NOSIGNAL) != 0);
1254 	flags &= ~MSG_NOSIGNAL;
1255 
1256 	size_t bytesLeft = length;
1257 	if (length > SSIZE_MAX)
1258 		return B_BAD_VALUE;
1259 
1260 	ancillary_data_container* ancillaryData = NULL;
1261 	CObjectDeleter<
1262 		ancillary_data_container, void, delete_ancillary_data_container>
1263 		ancillaryDataDeleter;
1264 
1265 	const sockaddr* address = NULL;
1266 	socklen_t addressLength = 0;
1267 	if (header != NULL) {
1268 		address = (const sockaddr*)header->msg_name;
1269 		addressLength = header->msg_namelen;
1270 
1271 		// get the ancillary data
1272 		if (header->msg_control != NULL) {
1273 			ancillaryData = create_ancillary_data_container();
1274 			if (ancillaryData == NULL)
1275 				return B_NO_MEMORY;
1276 			ancillaryDataDeleter.SetTo(ancillaryData);
1277 
1278 			status_t status = add_ancillary_data(socket, ancillaryData,
1279 				(cmsghdr*)header->msg_control, header->msg_controllen);
1280 			if (status != B_OK)
1281 				return status;
1282 		}
1283 	}
1284 
1285 	if (addressLength == 0)
1286 		address = NULL;
1287 	else if (address == NULL)
1288 		return B_BAD_VALUE;
1289 
1290 	if (socket->peer.ss_len != 0) {
1291 		if (address != NULL)
1292 			return EISCONN;
1293 
1294 		// socket is connected, we use that address
1295 		address = (struct sockaddr*)&socket->peer;
1296 		addressLength = socket->peer.ss_len;
1297 	}
1298 
1299 	if (address == NULL || addressLength == 0) {
1300 		// don't know where to send to:
1301 		return EDESTADDRREQ;
1302 	}
1303 
1304 	if ((socket->first_info->flags & NET_PROTOCOL_ATOMIC_MESSAGES) != 0
1305 		&& bytesLeft > socket->send.buffer_size)
1306 		return EMSGSIZE;
1307 
1308 	if (socket->address.ss_len == 0) {
1309 		// try to bind first
1310 		status_t status = socket_bind(socket, NULL, 0);
1311 		if (status != B_OK)
1312 			return status;
1313 	}
1314 
1315 	// If the protocol has a send_data_no_buffer() hook, we use that one.
1316 	if (socket->first_info->send_data_no_buffer != NULL) {
1317 		iovec stackVec = { (void*)data, length };
1318 		iovec* vecs = header ? header->msg_iov : &stackVec;
1319 		int vecCount = header ? header->msg_iovlen : 1;
1320 
1321 		ssize_t written = socket->first_info->send_data_no_buffer(
1322 			socket->first_protocol, vecs, vecCount, ancillaryData, address,
1323 			addressLength, flags);
1324 
1325 		// we only send signals when called from userland
1326 		if (written == EPIPE && is_syscall() && !nosignal)
1327 			send_signal(find_thread(NULL), SIGPIPE);
1328 
1329 		if (written > 0)
1330 			ancillaryDataDeleter.Detach();
1331 		return written;
1332 	}
1333 
1334 	// By convention, if a header is given, the (data, length) equals the first
1335 	// iovec. So drop the header, if it is the only iovec. Otherwise compute
1336 	// the size of the remaining ones.
1337 	if (header != NULL) {
1338 		if (header->msg_iovlen <= 1) {
1339 			header = NULL;
1340 		} else {
1341 			for (int i = 1; i < header->msg_iovlen; i++)
1342 				bytesLeft += header->msg_iov[i].iov_len;
1343 		}
1344 	}
1345 
1346 	ssize_t bytesSent = 0;
1347 	size_t vecOffset = 0;
1348 	uint32 vecIndex = 0;
1349 
1350 	while (bytesLeft > 0) {
1351 		// TODO: useful, maybe even computed header space!
1352 		net_buffer* buffer = gNetBufferModule.create(256);
1353 		if (buffer == NULL)
1354 			return ENOBUFS;
1355 
1356 		while (buffer->size < socket->send.buffer_size
1357 			&& buffer->size < bytesLeft) {
1358 			if (vecIndex > 0 && vecOffset == 0) {
1359 				// retrieve next iovec buffer from header
1360 				data = header->msg_iov[vecIndex].iov_base;
1361 				length = header->msg_iov[vecIndex].iov_len;
1362 			}
1363 
1364 			size_t bytes = length;
1365 			if (buffer->size + bytes > socket->send.buffer_size)
1366 				bytes = socket->send.buffer_size - buffer->size;
1367 
1368 			if (gNetBufferModule.append(buffer, data, bytes) < B_OK) {
1369 				gNetBufferModule.free(buffer);
1370 				return ENOBUFS;
1371 			}
1372 
1373 			if (bytes != length) {
1374 				// partial send
1375 				vecOffset = bytes;
1376 				length -= vecOffset;
1377 				data = (uint8*)data + vecOffset;
1378 			} else if (header != NULL) {
1379 				// proceed with next buffer, if any
1380 				vecOffset = 0;
1381 				vecIndex++;
1382 
1383 				if (vecIndex >= (uint32)header->msg_iovlen)
1384 					break;
1385 			}
1386 		}
1387 
1388 		// attach ancillary data to the first buffer
1389 		status_t status;
1390 		if (ancillaryData != NULL) {
1391 			gNetBufferModule.set_ancillary_data(buffer, ancillaryData);
1392 			ancillaryDataDeleter.Detach();
1393 			ancillaryData = NULL;
1394 		}
1395 
1396 		size_t bufferSize = buffer->size;
1397 		buffer->flags = flags;
1398 		memcpy(buffer->source, &socket->address, socket->address.ss_len);
1399 		memcpy(buffer->destination, address, addressLength);
1400 		buffer->destination->sa_len = addressLength;
1401 
1402 		status = socket->first_info->send_data(socket->first_protocol, buffer);
1403 		if (status != B_OK) {
1404 			// we only send signals when called from userland
1405 			if (status == EPIPE && is_syscall() && !nosignal)
1406 				send_signal(find_thread(NULL), SIGPIPE);
1407 
1408 			size_t sizeAfterSend = buffer->size;
1409 			gNetBufferModule.free(buffer);
1410 
1411 			if ((sizeAfterSend != bufferSize || bytesSent > 0)
1412 				&& (status == B_INTERRUPTED || status == B_WOULD_BLOCK)) {
1413 				// this appears to be a partial write
1414 				return bytesSent + (bufferSize - sizeAfterSend);
1415 			}
1416 			return status;
1417 		}
1418 
1419 		bytesLeft -= bufferSize;
1420 		bytesSent += bufferSize;
1421 	}
1422 
1423 	return bytesSent;
1424 }
1425 
1426 
1427 status_t
1428 socket_set_option(net_socket* socket, int level, int option, const void* value,
1429 	int length)
1430 {
1431 	if (level != SOL_SOCKET)
1432 		return ENOPROTOOPT;
1433 
1434 	TRACE("%s(socket %p, option %d\n", __FUNCTION__, socket, option);
1435 
1436 	switch (option) {
1437 		// TODO: implement other options!
1438 		case SO_LINGER:
1439 		{
1440 			if (length < (int)sizeof(struct linger))
1441 				return B_BAD_VALUE;
1442 
1443 			struct linger* linger = (struct linger*)value;
1444 			if (linger->l_onoff) {
1445 				socket->options |= SO_LINGER;
1446 				socket->linger = linger->l_linger;
1447 			} else {
1448 				socket->options &= ~SO_LINGER;
1449 				socket->linger = 0;
1450 			}
1451 			return B_OK;
1452 		}
1453 
1454 		case SO_SNDBUF:
1455 			if (length != sizeof(uint32))
1456 				return B_BAD_VALUE;
1457 
1458 			socket->send.buffer_size = *(const uint32*)value;
1459 			return B_OK;
1460 
1461 		case SO_RCVBUF:
1462 			if (length != sizeof(uint32))
1463 				return B_BAD_VALUE;
1464 
1465 			socket->receive.buffer_size = *(const uint32*)value;
1466 			return B_OK;
1467 
1468 		case SO_SNDLOWAT:
1469 			if (length != sizeof(uint32))
1470 				return B_BAD_VALUE;
1471 
1472 			socket->send.low_water_mark = *(const uint32*)value;
1473 			return B_OK;
1474 
1475 		case SO_RCVLOWAT:
1476 			if (length != sizeof(uint32))
1477 				return B_BAD_VALUE;
1478 
1479 			socket->receive.low_water_mark = *(const uint32*)value;
1480 			return B_OK;
1481 
1482 		case SO_RCVTIMEO:
1483 		case SO_SNDTIMEO:
1484 		{
1485 			if (length != sizeof(struct timeval))
1486 				return B_BAD_VALUE;
1487 
1488 			const struct timeval* timeval = (const struct timeval*)value;
1489 			bigtime_t timeout = timeval->tv_sec * 1000000LL + timeval->tv_usec;
1490 			if (timeout == 0)
1491 				timeout = B_INFINITE_TIMEOUT;
1492 
1493 			if (option == SO_SNDTIMEO)
1494 				socket->send.timeout = timeout;
1495 			else
1496 				socket->receive.timeout = timeout;
1497 			return B_OK;
1498 		}
1499 
1500 		case SO_NONBLOCK:
1501 			if (length != sizeof(int32))
1502 				return B_BAD_VALUE;
1503 
1504 			if (*(const int32*)value) {
1505 				socket->send.timeout = 0;
1506 				socket->receive.timeout = 0;
1507 			} else {
1508 				socket->send.timeout = B_INFINITE_TIMEOUT;
1509 				socket->receive.timeout = B_INFINITE_TIMEOUT;
1510 			}
1511 			return B_OK;
1512 
1513 		case SO_BROADCAST:
1514 		case SO_DEBUG:
1515 		case SO_DONTROUTE:
1516 		case SO_KEEPALIVE:
1517 		case SO_OOBINLINE:
1518 		case SO_REUSEADDR:
1519 		case SO_REUSEPORT:
1520 		case SO_USELOOPBACK:
1521 			if (length != sizeof(int32))
1522 				return B_BAD_VALUE;
1523 
1524 			if (*(const int32*)value)
1525 				socket->options |= option;
1526 			else
1527 				socket->options &= ~option;
1528 			return B_OK;
1529 
1530 		case SO_BINDTODEVICE:
1531 		{
1532 			if (length != sizeof(uint32))
1533 				return B_BAD_VALUE;
1534 
1535 			// TODO: we might want to check if the device exists at all
1536 			// (although it doesn't really harm when we don't)
1537 			socket->bound_to_device = *(const uint32*)value;
1538 			return B_OK;
1539 		}
1540 
1541 		default:
1542 			break;
1543 	}
1544 
1545 	dprintf("socket_setsockopt: unknown option %d\n", option);
1546 	return ENOPROTOOPT;
1547 }
1548 
1549 
1550 int
1551 socket_setsockopt(net_socket* socket, int level, int option, const void* value,
1552 	int length)
1553 {
1554 	return socket->first_protocol->module->setsockopt(socket->first_protocol,
1555 		level, option, value, length);
1556 }
1557 
1558 
1559 int
1560 socket_shutdown(net_socket* socket, int direction)
1561 {
1562 	return socket->first_info->shutdown(socket->first_protocol, direction);
1563 }
1564 
1565 
1566 status_t
1567 socket_socketpair(int family, int type, int protocol, net_socket* sockets[2])
1568 {
1569 	sockets[0] = NULL;
1570 	sockets[1] = NULL;
1571 
1572 	// create sockets
1573 	status_t error = socket_open(family, type, protocol, &sockets[0]);
1574 	if (error != B_OK)
1575 		return error;
1576 
1577 	error = socket_open(family, type, protocol, &sockets[1]);
1578 
1579 	// bind one
1580 	if (error == B_OK)
1581 		error = socket_bind(sockets[0], NULL, 0);
1582 
1583 	// start listening
1584 	if (error == B_OK && type == SOCK_STREAM)
1585 		error = socket_listen(sockets[0], 1);
1586 
1587 	// connect them
1588 	if (error == B_OK) {
1589 		error = socket_connect(sockets[1], (sockaddr*)&sockets[0]->address,
1590 			sockets[0]->address.ss_len);
1591 	}
1592 
1593 	if (error == B_OK) {
1594 		// accept a socket
1595 		if (type == SOCK_STREAM) {
1596 			net_socket* acceptedSocket = NULL;
1597 			error = socket_accept(sockets[0], NULL, NULL, &acceptedSocket);
1598 			if (error == B_OK) {
1599 				// everything worked: close the listener socket
1600 				socket_close(sockets[0]);
1601 				socket_free(sockets[0]);
1602 				sockets[0] = acceptedSocket;
1603 			}
1604 		// connect the other side
1605 		} else {
1606 			error = socket_connect(sockets[0], (sockaddr*)&sockets[1]->address,
1607 				sockets[1]->address.ss_len);
1608 		}
1609 	}
1610 
1611 	if (error != B_OK) {
1612 		// close sockets on error
1613 		for (int i = 0; i < 2; i++) {
1614 			if (sockets[i] != NULL) {
1615 				socket_close(sockets[i]);
1616 				socket_free(sockets[i]);
1617 				sockets[i] = NULL;
1618 			}
1619 		}
1620 	}
1621 
1622 	return error;
1623 }
1624 
1625 
1626 //	#pragma mark -
1627 
1628 
1629 static status_t
1630 socket_std_ops(int32 op, ...)
1631 {
1632 	switch (op) {
1633 		case B_MODULE_INIT:
1634 		{
1635 			new (&sSocketList) SocketList;
1636 			mutex_init(&sSocketLock, "socket list");
1637 
1638 #if ENABLE_DEBUGGER_COMMANDS
1639 			add_debugger_command("sockets", dump_sockets, "lists all sockets");
1640 			add_debugger_command("socket", dump_socket, "dumps a socket");
1641 #endif
1642 			return B_OK;
1643 		}
1644 		case B_MODULE_UNINIT:
1645 			ASSERT(sSocketList.IsEmpty());
1646 			mutex_destroy(&sSocketLock);
1647 
1648 #if ENABLE_DEBUGGER_COMMANDS
1649 			remove_debugger_command("socket", dump_socket);
1650 			remove_debugger_command("sockets", dump_sockets);
1651 #endif
1652 			return B_OK;
1653 
1654 		default:
1655 			return B_ERROR;
1656 	}
1657 }
1658 
1659 
1660 net_socket_module_info gNetSocketModule = {
1661 	{
1662 		NET_SOCKET_MODULE_NAME,
1663 		0,
1664 		socket_std_ops
1665 	},
1666 	socket_open,
1667 	socket_close,
1668 	socket_free,
1669 
1670 	socket_control,
1671 
1672 	socket_read_avail,
1673 	socket_send_avail,
1674 
1675 	socket_send_data,
1676 	socket_receive_data,
1677 
1678 	socket_get_option,
1679 	socket_set_option,
1680 
1681 	socket_get_next_stat,
1682 
1683 	// connections
1684 	socket_acquire,
1685 	socket_release,
1686 	socket_spawn_pending,
1687 	socket_dequeue_connected,
1688 	socket_count_connected,
1689 	socket_set_max_backlog,
1690 	socket_has_parent,
1691 	socket_connected,
1692 	socket_aborted,
1693 
1694 	// notifications
1695 	socket_request_notification,
1696 	socket_cancel_notification,
1697 	socket_notify,
1698 
1699 	// standard socket API
1700 	socket_accept,
1701 	socket_bind,
1702 	socket_connect,
1703 	socket_getpeername,
1704 	socket_getsockname,
1705 	socket_getsockopt,
1706 	socket_listen,
1707 	socket_receive,
1708 	socket_send,
1709 	socket_setsockopt,
1710 	socket_shutdown,
1711 	socket_socketpair
1712 };
1713 
1714