Index: src/Makefile ================================================================== --- src/Makefile +++ src/Makefile @@ -136,10 +136,11 @@ SRCS_PLUGINS = OFPlugin.m SRCS_SOCKETS = OFDNSQuery.m \ OFDNSResolver.m \ OFDNSResourceRecord.m \ OFDNSResponse.m \ + OFDatagramSocket.m \ OFHTTPClient.m \ OFHTTPCookie.m \ OFHTTPCookieManager.m \ OFHTTPRequest.m \ OFHTTPResponse.m \ ADDED src/OFDatagramSocket.h Index: src/OFDatagramSocket.h ================================================================== --- src/OFDatagramSocket.h +++ src/OFDatagramSocket.h @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, + * 2018, 2019, 2020 + * Jonathan Schleifer + * + * All rights reserved. + * + * This file is part of ObjFW. It may be distributed under the terms of the + * Q Public License 1.0, which can be found in the file LICENSE.QPL included in + * the packaging of this file. + * + * Alternatively, it may be distributed under the terms of the GNU General + * Public License, either version 2 or 3, which can be found in the file + * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this + * file. + */ + +#import "OFObject.h" +#import "OFKernelEventObserver.h" +#import "OFRunLoop.h" + +#import "socket.h" + +OF_ASSUME_NONNULL_BEGIN + +/*! @file */ + +@class OFDatagramSocket; + +#ifdef OF_HAVE_BLOCKS +/*! + * @brief A block which is called when a packet has been received. + * + * @param socket The datagram socket which received a packet + * @param buffer The buffer the packet has been written to + * @param length The length of the packet + * @param sender The address of the sender of the packet + * @param exception An exception which occurred while receiving or `nil` on + * success + * @return A bool whether the same block should be used for the next receive + */ +typedef bool (^of_datagram_socket_async_receive_block_t)( + OFDatagramSocket *_Nonnull socket, void *_Nonnull buffer, size_t length, + const of_socket_address_t *_Nonnull sender, id _Nullable exception); + +/*! + * @brief A block which is called when a packet has been sent. + * + * @param socket The datagram socket which sent a packet + * @param data The data which was sent + * @param receiver The receiver for the packet + * @param exception An exception which occurred while reading or `nil` on + * success + * @return The data to repeat the send with or nil if it should not repeat + */ +typedef OFData *_Nullable (^of_datagram_socket_async_send_data_block_t)( + OFDatagramSocket *_Nonnull socket, OFData *_Nonnull data, + const of_socket_address_t *_Nonnull receiver, id _Nullable exception); +#endif + +/*! + * @protocol OFDatagramSocketDelegate OFDatagramSocket.h \ + * ObjFW/OFDatagramSocket.h + * + * @brief A delegate for OFDatagramSocket. + */ +@protocol OFDatagramSocketDelegate +@optional +/*! + * @brief This method is called when a packet has been received. + * + * @param socket The datagram socket which received a packet + * @param buffer The buffer the packet has been written to + * @param length The length of the packet + * @param sender The address of the sender of the packet + * @param exception An exception that occurred while receiving, or nil on + * success + * @return A bool whether the same block should be used for the next receive + */ +- (bool)socket: (OFDatagramSocket *)socket + didReceiveIntoBuffer: (void *)buffer + length: (size_t)length + sender: (const of_socket_address_t *_Nonnull)sender + exception: (nullable id)exception; + +/*! + * @brief This which is called when a packet has been sent. + * + * @param socket The datagram socket which sent a packet + * @param data The data which was sent + * @param receiver The receiver for the packet + * @param exception An exception that occurred while sending, or nil on success + * @return The data to repeat the send with or nil if it should not repeat + */ +- (nullable OFData *)socket: (OFDatagramSocket *)socket + didSendData: (OFData *)data + receiver: (const of_socket_address_t *_Nonnull)receiver + exception: (nullable id)exception; +@end + +/*! + * @class OFDatagramSocket OFDatagramSocket.h ObjFW/OFDatagramSocket.h + * + * @brief A base class for datagram sockets. + * + * @warning Even though the OFCopying protocol is implemented, it does *not* + * return an independent copy of the socket, but instead retains it. + * This is so that the socket can be used as a key for a dictionary, + * so context can be associated with a socket. Using a socket in more + * than one thread at the same time is not thread-safe, even if copy + * was called to create one "instance" for every thread! + */ +@interface OFDatagramSocket: OFObject +{ + of_socket_t _socket; + bool _blocking; + id _Nullable _delegate; + OF_RESERVE_IVARS(4) +} + +/*! + * @brief Whether the socket is in blocking mode. + * + * By default, a socket is in blocking mode. + */ +@property (nonatomic, getter=isBlocking) bool blocking; + +/*! + * @brief The delegate for asynchronous operations on the socket. + * + * @note The delegate is retained for as long as asynchronous operations are + * still outstanding. + */ +@property OF_NULLABLE_PROPERTY (assign, nonatomic) + id delegate; + +/*! + * @brief Returns a new, autoreleased OFDatagramSocket. + * + * @return A new, autoreleased OFDatagramSocket + */ ++ (instancetype)socket; + +/*! + * @brief Receives a datagram and stores it into the specified buffer. + * + * If the buffer is too small, the datagram is truncated. + * + * @param buffer The buffer to write the datagram to + * @param length The length of the buffer + * @param sender A pointer to an @ref of_socket_address_t, which will be set to + * the address of the sender + * @return The length of the received datagram + */ +- (size_t)receiveIntoBuffer: (void *)buffer + length: (size_t)length + sender: (of_socket_address_t *)sender; + +/*! + * @brief Asynchronously receives a datagram and stores it into the specified + * buffer. + * + * If the buffer is too small, the datagram is truncated. + * + * @param buffer The buffer to write the datagram to + * @param length The length of the buffer + */ +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length; + +/*! + * @brief Asynchronously receives a datagram and stores it into the specified + * buffer. + * + * If the buffer is too small, the datagram is truncated. + * + * @param buffer The buffer to write the datagram to + * @param length The length of the buffer + * @param runLoopMode The run loop mode in which to perform the async receive + */ +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length + runLoopMode: (of_run_loop_mode_t)runLoopMode; + +#ifdef OF_HAVE_BLOCKS +/*! + * @brief Asynchronously receives a datagram and stores it into the specified + * buffer. + * + * If the buffer is too small, the datagram is truncated. + * + * @param buffer The buffer to write the datagram to + * @param length The length of the buffer + * @param block The block to call when the datagram has been received. If the + * block returns true, it will be called again with the same + * buffer and maximum length when more datagrams have been + * received. If you want the next method in the queue to handle + * the datagram received next, you need to return false from the + * method. + */ +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length + block: (of_datagram_socket_async_receive_block_t)block; + +/*! + * @brief Asynchronously receives a datagram and stores it into the specified + * buffer. + * + * If the buffer is too small, the datagram is truncated. + * + * @param buffer The buffer to write the datagram to + * @param length The length of the buffer + * @param runLoopMode The run loop mode in which to perform the async receive + * @param block The block to call when the datagram has been received. If the + * block returns true, it will be called again with the same + * buffer and maximum length when more datagrams have been + * received. If you want the next method in the queue to handle + * the datagram received next, you need to return false from the + * method. + */ +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length + runLoopMode: (of_run_loop_mode_t)runLoopMode + block: (of_datagram_socket_async_receive_block_t)block; +#endif + +/*! + * @brief Sends the specified datagram to the specified address. + * + * @param buffer The buffer to send as a datagram + * @param length The length of the buffer + * @param receiver A pointer to an @ref of_socket_address_t to which the + * datagram should be sent + */ +- (void)sendBuffer: (const void *)buffer + length: (size_t)length + receiver: (const of_socket_address_t *)receiver; + +/*! + * @brief Asynchronously sends the specified datagram to the specified address. + * + * @param data The data to send as a datagram + * @param receiver A pointer to an @ref of_socket_address_t to which the + * datagram should be sent. The receiver is copied. + */ +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver; + +/*! + * @brief Asynchronously sends the specified datagram to the specified address. + * + * @param data The data to send as a datagram + * @param receiver A pointer to an @ref of_socket_address_t to which the + * datagram should be sent. The receiver is copied. + * @param runLoopMode The run loop mode in which to perform the async send + */ +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver + runLoopMode: (of_run_loop_mode_t)runLoopMode; + +#ifdef OF_HAVE_BLOCKS +/*! + * @brief Asynchronously sends the specified datagram to the specified address. + * + * @param data The data to send as a datagram + * @param receiver A pointer to an @ref of_socket_address_t to which the + * datagram should be sent. The receiver is copied. + * @param block The block to call when the packet has been sent. It should + * return the data for the next send with the same callback or nil + * if it should not repeat. + */ +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver + block: (of_datagram_socket_async_send_data_block_t)block; + +/*! + * @brief Asynchronously sends the specified datagram to the specified address. + * + * @param data The data to send as a datagram + * @param receiver A pointer to an @ref of_socket_address_t to which the + * datagram should be sent. The receiver is copied. + * @param runLoopMode The run loop mode in which to perform the async send + * @param block The block to call when the packet has been sent. It should + * return the data for the next send with the same callback or nil + * if it should not repeat. + */ +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver + runLoopMode: (of_run_loop_mode_t)runLoopMode + block: (of_datagram_socket_async_send_data_block_t)block; +#endif + +/*! + * @brief Cancels all pending asynchronous requests on the socket. + */ +- (void)cancelAsyncRequests; + +/*! + * @brief Closes the socket so that it can neither receive nor send any more + * datagrams. + */ +- (void)close; +@end + +OF_ASSUME_NONNULL_END ADDED src/OFDatagramSocket.m Index: src/OFDatagramSocket.m ================================================================== --- src/OFDatagramSocket.m +++ src/OFDatagramSocket.m @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, + * 2018, 2019, 2020 + * Jonathan Schleifer + * + * All rights reserved. + * + * This file is part of ObjFW. It may be distributed under the terms of the + * Q Public License 1.0, which can be found in the file LICENSE.QPL included in + * the packaging of this file. + * + * Alternatively, it may be distributed under the terms of the GNU General + * Public License, either version 2 or 3, which can be found in the file + * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this + * file. + */ + +#include "config.h" + +#include +#include +#include + +#ifdef HAVE_FCNTL_H +# include +#endif + +#import "OFDatagramSocket.h" +#import "OFData.h" +#import "OFRunLoop+Private.h" +#import "OFRunLoop.h" + +#import "OFInitializationFailedException.h" +#import "OFInvalidFormatException.h" +#import "OFNotOpenException.h" +#import "OFOutOfRangeException.h" +#import "OFReadFailedException.h" +#import "OFSetOptionFailedException.h" +#import "OFWriteFailedException.h" + +#import "socket.h" +#import "socket_helpers.h" + +@implementation OFDatagramSocket +@synthesize delegate = _delegate; + ++ (void)initialize +{ + if (self != [OFDatagramSocket class]) + return; + + if (!of_socket_init()) + @throw [OFInitializationFailedException + exceptionWithClass: self]; +} + ++ (instancetype)socket +{ + return [[[self alloc] init] autorelease]; +} + +- (instancetype)init +{ + self = [super init]; + + @try { + if (self.class == [OFDatagramSocket class]) { + [self doesNotRecognizeSelector: _cmd]; + abort(); + } + + _socket = INVALID_SOCKET; + _blocking = true; + } @catch (id e) { + [self release]; + @throw e; + } + + return self; +} + +- (void)dealloc +{ + if (_socket != INVALID_SOCKET) + [self close]; + + [super dealloc]; +} + +- (id)copy +{ + return [self retain]; +} + +- (bool)isBlocking +{ + return _blocking; +} + +- (void)setBlocking: (bool)enable +{ +#if defined(HAVE_FCNTL) + int flags = fcntl(_socket, F_GETFL, 0); + + if (flags == -1) + @throw [OFSetOptionFailedException exceptionWithObject: self + errNo: errno]; + + if (enable) + flags &= ~O_NONBLOCK; + else + flags |= O_NONBLOCK; + + if (fcntl(_socket, F_SETFL, flags) == -1) + @throw [OFSetOptionFailedException exceptionWithObject: self + errNo: errno]; + + _blocking = enable; +#elif defined(OF_WINDOWS) + u_long v = enable; + + if (ioctlsocket(_socket, FIONBIO, &v) == SOCKET_ERROR) + @throw [OFSetOptionFailedException + exceptionWithObject: self + errNo: of_socket_errno()]; + + _blocking = enable; +#else + OF_UNRECOGNIZED_SELECTOR +#endif +} + +- (size_t)receiveIntoBuffer: (void *)buffer + length: (size_t)length + sender: (of_socket_address_t *)sender +{ + ssize_t ret; + + if (_socket == INVALID_SOCKET) + @throw [OFNotOpenException exceptionWithObject: self]; + + sender->length = (socklen_t)sizeof(sender->sockaddr); + +#ifndef OF_WINDOWS + if ((ret = recvfrom(_socket, buffer, length, 0, + &sender->sockaddr.sockaddr, &sender->length)) < 0) + @throw [OFReadFailedException + exceptionWithObject: self + requestedLength: length + errNo: of_socket_errno()]; +#else + if (length > INT_MAX) + @throw [OFOutOfRangeException exception]; + + if ((ret = recvfrom(_socket, buffer, (int)length, 0, + &sender->sockaddr.sockaddr, &sender->length)) < 0) + @throw [OFReadFailedException + exceptionWithObject: self + requestedLength: length + errNo: of_socket_errno()]; +#endif + + switch (sender->sockaddr.sockaddr.sa_family) { + case AF_INET: + sender->family = OF_SOCKET_ADDRESS_FAMILY_IPV4; + break; +#ifdef OF_HAVE_IPV6 + case AF_INET6: + sender->family = OF_SOCKET_ADDRESS_FAMILY_IPV6; + break; +#endif + default: + sender->family = OF_SOCKET_ADDRESS_FAMILY_UNKNOWN; + break; + } + + return ret; +} + +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length +{ + [self asyncReceiveIntoBuffer: buffer + length: length + runLoopMode: of_run_loop_mode_default]; +} + +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length + runLoopMode: (of_run_loop_mode_t)runLoopMode +{ + [OFRunLoop of_addAsyncReceiveForDatagramSocket: self + buffer: buffer + length: length + mode: runLoopMode +# ifdef OF_HAVE_BLOCKS + block: NULL +# endif + delegate: _delegate]; +} + +#ifdef OF_HAVE_BLOCKS +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length + block: (of_datagram_socket_async_receive_block_t)block +{ + [self asyncReceiveIntoBuffer: buffer + length: length + runLoopMode: of_run_loop_mode_default + block: block]; +} + +- (void)asyncReceiveIntoBuffer: (void *)buffer + length: (size_t)length + runLoopMode: (of_run_loop_mode_t)runLoopMode + block: (of_datagram_socket_async_receive_block_t)block +{ + [OFRunLoop of_addAsyncReceiveForDatagramSocket: self + buffer: buffer + length: length + mode: runLoopMode + block: block + delegate: nil]; +} +#endif + +- (void)sendBuffer: (const void *)buffer + length: (size_t)length + receiver: (const of_socket_address_t *)receiver +{ + if (_socket == INVALID_SOCKET) + @throw [OFNotOpenException exceptionWithObject: self]; + +#ifndef OF_WINDOWS + ssize_t bytesWritten; + + if (length > SSIZE_MAX) + @throw [OFOutOfRangeException exception]; + + if ((bytesWritten = sendto(_socket, (void *)buffer, length, 0, + (struct sockaddr *)&receiver->sockaddr.sockaddr, + receiver->length)) < 0) + @throw [OFWriteFailedException + exceptionWithObject: self + requestedLength: length + bytesWritten: 0 + errNo: of_socket_errno()]; +#else + int bytesWritten; + + if (length > INT_MAX) + @throw [OFOutOfRangeException exception]; + + if ((bytesWritten = sendto(_socket, buffer, (int)length, 0, + &receiver->sockaddr.sockaddr, receiver->length)) < 0) + @throw [OFWriteFailedException + exceptionWithObject: self + requestedLength: length + bytesWritten: 0 + errNo: of_socket_errno()]; +#endif + + if ((size_t)bytesWritten != length) + @throw [OFWriteFailedException exceptionWithObject: self + requestedLength: length + bytesWritten: bytesWritten + errNo: 0]; +} + +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver +{ + [self asyncSendData: data + receiver: receiver + runLoopMode: of_run_loop_mode_default]; +} + +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver + runLoopMode: (of_run_loop_mode_t)runLoopMode +{ + [OFRunLoop of_addAsyncSendForDatagramSocket: self + data: data + receiver: receiver + mode: runLoopMode +# ifdef OF_HAVE_BLOCKS + block: NULL +# endif + delegate: _delegate]; +} + +#ifdef OF_HAVE_BLOCKS +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver + block: (of_datagram_socket_async_send_data_block_t)block +{ + [self asyncSendData: data + receiver: receiver + runLoopMode: of_run_loop_mode_default + block: block]; +} + +- (void)asyncSendData: (OFData *)data + receiver: (const of_socket_address_t *)receiver + runLoopMode: (of_run_loop_mode_t)runLoopMode + block: (of_datagram_socket_async_send_data_block_t)block +{ + [OFRunLoop of_addAsyncSendForDatagramSocket: self + data: data + receiver: receiver + mode: runLoopMode + block: block + delegate: nil]; +} +#endif + +- (void)cancelAsyncRequests +{ + [OFRunLoop of_cancelAsyncRequestsForObject: self + mode: of_run_loop_mode_default]; +} + +- (int)fileDescriptorForReading +{ +#ifndef OF_WINDOWS + return _socket; +#else + if (_socket == INVALID_SOCKET) + return -1; + + if (_socket > INT_MAX) + @throw [OFOutOfRangeException exception]; + + return (int)_socket; +#endif +} + +- (int)fileDescriptorForWriting +{ +#ifndef OF_WINDOWS + return _socket; +#else + if (_socket == INVALID_SOCKET) + return -1; + + if (_socket > INT_MAX) + @throw [OFOutOfRangeException exception]; + + return (int)_socket; +#endif +} + +- (void)close +{ + if (_socket == INVALID_SOCKET) + @throw [OFNotOpenException exceptionWithObject: self]; + + closesocket(_socket); + _socket = INVALID_SOCKET; +} +@end Index: src/OFRunLoop+Private.h ================================================================== --- src/OFRunLoop+Private.h +++ src/OFRunLoop+Private.h @@ -17,11 +17,11 @@ #import "OFRunLoop.h" #import "OFStream.h" #ifdef OF_HAVE_SOCKETS # import "OFTCPSocket.h" -# import "OFUDPSocket.h" +# import "OFDatagramSocket.h" #endif OF_ASSUME_NONNULL_BEGIN #ifdef OF_HAVE_SOCKETS @@ -95,35 +95,29 @@ of_tcp_socket_async_accept_block_t) block # endif delegate: (nullable id ) delegate; -+ (void)of_addAsyncReceiveForUDPSocket: (OFUDPSocket *)socket - buffer: (void *)buffer - length: (size_t)length - mode: (of_run_loop_mode_t)mode -# ifdef OF_HAVE_BLOCKS - block: (nullable - of_udp_socket_async_receive_block_t) - block -# endif - delegate: (nullable id ) - delegate; -+ (void)of_addAsyncSendForUDPSocket: (OFUDPSocket *)socket - data: (OFData *)data - receiver: (const of_socket_address_t *)receiver - mode: (of_run_loop_mode_t)mode -# ifdef OF_HAVE_BLOCKS - block: (nullable - of_udp_socket_async_send_data_block_t) - block -# endif - delegate: (nullable id ) - delegate; ++ (void)of_addAsyncReceiveForDatagramSocket: (OFDatagramSocket *)socket + buffer: (void *)buffer + length: (size_t)length + mode: (of_run_loop_mode_t)mode +# ifdef OF_HAVE_BLOCKS + block: (nullable of_datagram_socket_async_receive_block_t)block +# endif + delegate: (nullable id ) delegate; ++ (void)of_addAsyncSendForDatagramSocket: (OFDatagramSocket *)socket + data: (OFData *)data + receiver: (const of_socket_address_t *)receiver + mode: (of_run_loop_mode_t)mode +# ifdef OF_HAVE_BLOCKS + block: (nullable of_datagram_socket_async_send_data_block_t)block +# endif + delegate: (nullable id )delegate; + (void)of_cancelAsyncRequestsForObject: (id)object mode: (of_run_loop_mode_t)mode; #endif - (void)of_removeTimer: (OFTimer *)timer forMode: (of_run_loop_mode_t)mode; @end OF_ASSUME_NONNULL_END Index: src/OFRunLoop.m ================================================================== --- src/OFRunLoop.m +++ src/OFRunLoop.m @@ -160,26 +160,26 @@ of_tcp_socket_async_accept_block_t _block; # endif } @end -@interface OFRunLoopUDPReceiveQueueItem: OFRunLoopQueueItem +@interface OFRunLoopDatagramReceiveQueueItem: OFRunLoopQueueItem { @public # ifdef OF_HAVE_BLOCKS - of_udp_socket_async_receive_block_t _block; + of_datagram_socket_async_receive_block_t _block; # endif void *_buffer; size_t _length; } @end -@interface OFRunLoopUDPSendQueueItem: OFRunLoopQueueItem +@interface OFRunLoopDatagramSendQueueItem: OFRunLoopQueueItem { @public # ifdef OF_HAVE_BLOCKS - of_udp_socket_async_send_data_block_t _block; + of_datagram_socket_async_send_data_block_t _block; # endif OFData *_data; of_socket_address_t _receiver; } @end @@ -770,11 +770,11 @@ [super dealloc]; } # endif @end -@implementation OFRunLoopUDPReceiveQueueItem +@implementation OFRunLoopDatagramReceiveQueueItem - (bool)handleObject: (id)object { size_t length; of_socket_address_t address; id exception = nil; @@ -815,11 +815,11 @@ [super dealloc]; } # endif @end -@implementation OFRunLoopUDPSendQueueItem +@implementation OFRunLoopDatagramSendQueueItem - (bool)handleObject: (id)object { id exception = nil; OFData *newData, *oldData; @@ -1080,21 +1080,20 @@ # endif QUEUE_ITEM } -+ (void)of_addAsyncReceiveForUDPSocket: (OFUDPSocket *)sock - buffer: (void *)buffer - length: (size_t)length - mode: (of_run_loop_mode_t)mode ++ (void)of_addAsyncReceiveForDatagramSocket: (OFDatagramSocket *)sock + buffer: (void *)buffer + length: (size_t)length + mode: (of_run_loop_mode_t)mode # ifdef OF_HAVE_BLOCKS - block: (of_udp_socket_async_receive_block_t) - block + block: (of_datagram_socket_async_receive_block_t)block # endif - delegate: (id )delegate + delegate: (id )delegate { - NEW_READ(OFRunLoopUDPReceiveQueueItem, sock, mode) + NEW_READ(OFRunLoopDatagramReceiveQueueItem, sock, mode) queueItem->_delegate = [delegate retain]; # ifdef OF_HAVE_BLOCKS queueItem->_block = [block copy]; # endif @@ -1102,21 +1101,20 @@ queueItem->_length = length; QUEUE_ITEM } -+ (void)of_addAsyncSendForUDPSocket: (OFUDPSocket *)sock - data: (OFData *)data - receiver: (const of_socket_address_t *)receiver - mode: (of_run_loop_mode_t)mode ++ (void)of_addAsyncSendForDatagramSocket: (OFDatagramSocket *)sock + data: (OFData *)data + receiver: (const of_socket_address_t *)receiver + mode: (of_run_loop_mode_t)mode # ifdef OF_HAVE_BLOCKS - block: (of_udp_socket_async_send_data_block_t) - block + block: (of_datagram_socket_async_send_data_block_t)block # endif - delegate: (id )delegate + delegate: (id )delegate { - NEW_WRITE(OFRunLoopUDPSendQueueItem, sock, mode) + NEW_WRITE(OFRunLoopDatagramSendQueueItem, sock, mode) queueItem->_delegate = [delegate retain]; # ifdef OF_HAVE_BLOCKS queueItem->_block = [block copy]; # endif Index: src/OFStream.m ================================================================== --- src/OFStream.m +++ src/OFStream.m @@ -73,23 +73,23 @@ } #endif - (instancetype)init { - if ([self isMemberOfClass: [OFStream class]]) { - @try { + self = [super init]; + + @try { + if (self.class == [OFStream class]) { [self doesNotRecognizeSelector: _cmd]; abort(); - } @catch (id e) { - [self release]; - @throw e; - } - } - - self = [super init]; - - _blocking = true; + } + + _blocking = true; + } @catch (id e) { + [self release]; + @throw e; + } return self; } - (bool)lowlevelIsAtEndOfStream Index: src/OFStreamSocket.m ================================================================== --- src/OFStreamSocket.m +++ src/OFStreamSocket.m @@ -47,10 +47,29 @@ + (instancetype)socket { return [[[self alloc] init] autorelease]; } + +- (instancetype)init +{ + self = [super init]; + + @try { + if (self.class == [OFStreamSocket class]) { + [self doesNotRecognizeSelector: _cmd]; + abort(); + } + + _socket = INVALID_SOCKET; + } @catch (id e) { + [self release]; + @throw e; + } + + return self; +} - (bool)lowlevelIsAtEndOfStream { if (_socket == INVALID_SOCKET) @throw [OFNotOpenException exceptionWithObject: self]; Index: src/OFUDPSocket.h ================================================================== --- src/OFUDPSocket.h +++ src/OFUDPSocket.h @@ -13,90 +13,22 @@ * Public License, either version 2 or 3, which can be found in the file * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this * file. */ -#import "OFObject.h" -#import "OFKernelEventObserver.h" -#import "OFRunLoop.h" - -#import "socket.h" +#import "OFDatagramSocket.h" OF_ASSUME_NONNULL_BEGIN -/*! @file */ - -@class OFUDPSocket; - -#ifdef OF_HAVE_BLOCKS -/*! - * @brief A block which is called when a packet has been received. - * - * @param socket The UDP socket which received a packet - * @param buffer The buffer the packet has been written to - * @param length The length of the packet - * @param sender The address of the sender of the packet - * @param exception An exception which occurred while receiving or `nil` on - * success - * @return A bool whether the same block should be used for the next receive - */ -typedef bool (^of_udp_socket_async_receive_block_t)( - OFUDPSocket *_Nonnull socket, void *_Nonnull buffer, size_t length, - const of_socket_address_t *_Nonnull sender, id _Nullable exception); - -/*! - * @brief A block which is called when a packet has been sent. - * - * @param socket The UDP socket which sent a packet - * @param data The data which was sent - * @param receiver The receiver for the UDP packet - * @param exception An exception which occurred while reading or `nil` on - * success - * @return The data to repeat the send with or nil if it should not repeat - */ -typedef OFData *_Nullable (^of_udp_socket_async_send_data_block_t)( - OFUDPSocket *_Nonnull socket, OFData *_Nonnull data, - const of_socket_address_t *_Nonnull receiver, id _Nullable exception); -#endif +@class OFString; /*! * @protocol OFUDPSocketDelegate OFUDPSocket.h ObjFW/OFUDPSocket.h * * @brief A delegate for OFUDPSocket. */ -@protocol OFUDPSocketDelegate -@optional -/*! - * @brief This method is called when a packet has been received. - * - * @param socket The UDP socket which received a packet - * @param buffer The buffer the packet has been written to - * @param length The length of the packet - * @param sender The address of the sender of the packet - * @param exception An exception that occurred while receiving, or nil on - * success - * @return A bool whether the same block should be used for the next receive - */ -- (bool)socket: (OFUDPSocket *)socket - didReceiveIntoBuffer: (void *)buffer - length: (size_t)length - sender: (const of_socket_address_t *_Nonnull)sender - exception: (nullable id)exception; - -/*! - * @brief This which is called when a packet has been sent. - * - * @param socket The UDP socket which sent a packet - * @param data The data which was sent - * @param receiver The receiver for the UDP packet - * @param exception An exception that occurred while sending, or nil on success - * @return The data to repeat the send with or nil if it should not repeat - */ -- (nullable OFData *)socket: (OFUDPSocket *)socket - didSendData: (OFData *)data - receiver: (const of_socket_address_t *_Nonnull)receiver - exception: (nullable id)exception; +@protocol OFUDPSocketDelegate @end /*! * @class OFUDPSocket OFUDPSocket.h ObjFW/OFUDPSocket.h * @@ -114,28 +46,16 @@ * This is so that the socket can be used as a key for a dictionary, * so context can be associated with a socket. Using a socket in more * than one thread at the same time is not thread-safe, even if copy * was called to create one "instance" for every thread! */ -@interface OFUDPSocket: OFObject +@interface OFUDPSocket: OFDatagramSocket { - of_socket_t _socket; #ifdef OF_WII uint16_t _port; #endif - bool _blocking; - id _Nullable _delegate; - OF_RESERVE_IVARS(4) -} - -/*! - * @brief Whether the socket is in blocking mode. - * - * By default, a socket is in blocking mode. - */ -@property (nonatomic, getter=isBlocking) bool blocking; +} /*! * @brief The delegate for asynchronous operations on the socket. * * @note The delegate is retained for as long as asynchronous operations are @@ -142,17 +62,10 @@ * still outstanding. */ @property OF_NULLABLE_PROPERTY (assign, nonatomic) id delegate; -/*! - * @brief Returns a new, autoreleased OFUDPSocket. - * - * @return A new, autoreleased OFUDPSocket - */ -+ (instancetype)socket; - /*! * @brief Binds the socket to the specified host and port. * * @param host The host to bind to. Use `@"0.0.0.0"` for IPv4 or `@"::"` for * IPv6 to bind to all. @@ -160,168 +73,8 @@ * chosen, which can be obtained using the return value. * @return The port the socket was bound to */ - (uint16_t)bindToHost: (OFString *)host port: (uint16_t)port; - -/*! - * @brief Receives a datagram and stores it into the specified buffer. - * - * If the buffer is too small, the datagram is truncated. - * - * @param buffer The buffer to write the datagram to - * @param length The length of the buffer - * @param sender A pointer to an @ref of_socket_address_t, which will be set to - * the address of the sender - * @return The length of the received datagram - */ -- (size_t)receiveIntoBuffer: (void *)buffer - length: (size_t)length - sender: (of_socket_address_t *)sender; - -/*! - * @brief Asynchronously receives a datagram and stores it into the specified - * buffer. - * - * If the buffer is too small, the datagram is truncated. - * - * @param buffer The buffer to write the datagram to - * @param length The length of the buffer - */ -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length; - -/*! - * @brief Asynchronously receives a datagram and stores it into the specified - * buffer. - * - * If the buffer is too small, the datagram is truncated. - * - * @param buffer The buffer to write the datagram to - * @param length The length of the buffer - * @param runLoopMode The run loop mode in which to perform the async receive - */ -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length - runLoopMode: (of_run_loop_mode_t)runLoopMode; - -#ifdef OF_HAVE_BLOCKS -/*! - * @brief Asynchronously receives a datagram and stores it into the specified - * buffer. - * - * If the buffer is too small, the datagram is truncated. - * - * @param buffer The buffer to write the datagram to - * @param length The length of the buffer - * @param block The block to call when the datagram has been received. If the - * block returns true, it will be called again with the same - * buffer and maximum length when more datagrams have been - * received. If you want the next method in the queue to handle - * the datagram received next, you need to return false from the - * method. - */ -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length - block: (of_udp_socket_async_receive_block_t)block; - -/*! - * @brief Asynchronously receives a datagram and stores it into the specified - * buffer. - * - * If the buffer is too small, the datagram is truncated. - * - * @param buffer The buffer to write the datagram to - * @param length The length of the buffer - * @param runLoopMode The run loop mode in which to perform the async receive - * @param block The block to call when the datagram has been received. If the - * block returns true, it will be called again with the same - * buffer and maximum length when more datagrams have been - * received. If you want the next method in the queue to handle - * the datagram received next, you need to return false from the - * method. - */ -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length - runLoopMode: (of_run_loop_mode_t)runLoopMode - block: (of_udp_socket_async_receive_block_t)block; -#endif - -/*! - * @brief Sends the specified datagram to the specified address. - * - * @param buffer The buffer to send as a datagram - * @param length The length of the buffer - * @param receiver A pointer to an @ref of_socket_address_t to which the - * datagram should be sent - */ -- (void)sendBuffer: (const void *)buffer - length: (size_t)length - receiver: (const of_socket_address_t *)receiver; - -/*! - * @brief Asynchronously sends the specified datagram to the specified address. - * - * @param data The data to send as a datagram - * @param receiver A pointer to an @ref of_socket_address_t to which the - * datagram should be sent. The receiver is copied. - */ -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver; - -/*! - * @brief Asynchronously sends the specified datagram to the specified address. - * - * @param data The data to send as a datagram - * @param receiver A pointer to an @ref of_socket_address_t to which the - * datagram should be sent. The receiver is copied. - * @param runLoopMode The run loop mode in which to perform the async send - */ -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver - runLoopMode: (of_run_loop_mode_t)runLoopMode; - -#ifdef OF_HAVE_BLOCKS -/*! - * @brief Asynchronously sends the specified datagram to the specified address. - * - * @param data The data to send as a datagram - * @param receiver A pointer to an @ref of_socket_address_t to which the - * datagram should be sent. The receiver is copied. - * @param block The block to call when the packet has been sent. It should - * return the data for the next send with the same callback or nil - * if it should not repeat. - */ -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver - block: (of_udp_socket_async_send_data_block_t)block; - -/*! - * @brief Asynchronously sends the specified datagram to the specified address. - * - * @param data The data to send as a datagram - * @param receiver A pointer to an @ref of_socket_address_t to which the - * datagram should be sent. The receiver is copied. - * @param runLoopMode The run loop mode in which to perform the async send - * @param block The block to call when the packet has been sent. It should - * return the data for the next send with the same callback or nil - * if it should not repeat. - */ -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver - runLoopMode: (of_run_loop_mode_t)runLoopMode - block: (of_udp_socket_async_send_data_block_t)block; -#endif - -/*! - * @brief Cancels all pending asynchronous requests on the socket. - */ -- (void)cancelAsyncRequests; - -/*! - * @brief Closes the socket so that it can neither receive nor send any more - * datagrams. - */ -- (void)close; @end OF_ASSUME_NONNULL_END Index: src/OFUDPSocket.m ================================================================== --- src/OFUDPSocket.m +++ src/OFUDPSocket.m @@ -15,118 +15,30 @@ * file. */ #include "config.h" -#include #include -#include #ifdef HAVE_FCNTL_H # include #endif #import "OFUDPSocket.h" #import "OFUDPSocket+Private.h" #import "OFDNSResolver.h" #import "OFData.h" -#import "OFRunLoop+Private.h" -#import "OFRunLoop.h" #import "OFThread.h" #import "OFAlreadyConnectedException.h" #import "OFBindFailedException.h" -#import "OFInitializationFailedException.h" -#import "OFInvalidArgumentException.h" -#import "OFInvalidFormatException.h" -#import "OFNotOpenException.h" -#import "OFOutOfRangeException.h" -#import "OFReadFailedException.h" -#import "OFSetOptionFailedException.h" -#import "OFWriteFailedException.h" #import "socket.h" #import "socket_helpers.h" @implementation OFUDPSocket -@synthesize delegate = _delegate; - -+ (void)initialize -{ - if (self != [OFUDPSocket class]) - return; - - if (!of_socket_init()) - @throw [OFInitializationFailedException - exceptionWithClass: self]; -} - -+ (instancetype)socket -{ - return [[[self alloc] init] autorelease]; -} - -- (instancetype)init -{ - self = [super init]; - - _socket = INVALID_SOCKET; - _blocking = true; - - return self; -} - -- (void)dealloc -{ - if (_socket != INVALID_SOCKET) - [self close]; - - [super dealloc]; -} - -- (id)copy -{ - return [self retain]; -} - -- (bool)isBlocking -{ - return _blocking; -} - -- (void)setBlocking: (bool)enable -{ -#if defined(HAVE_FCNTL) - int flags = fcntl(_socket, F_GETFL, 0); - - if (flags == -1) - @throw [OFSetOptionFailedException exceptionWithObject: self - errNo: errno]; - - if (enable) - flags &= ~O_NONBLOCK; - else - flags |= O_NONBLOCK; - - if (fcntl(_socket, F_SETFL, flags) == -1) - @throw [OFSetOptionFailedException exceptionWithObject: self - errNo: errno]; - - _blocking = enable; -#elif defined(OF_WINDOWS) - u_long v = enable; - - if (ioctlsocket(_socket, FIONBIO, &v) == SOCKET_ERROR) - @throw [OFSetOptionFailedException - exceptionWithObject: self - errNo: of_socket_errno()]; - - _blocking = enable; -#else - OF_UNRECOGNIZED_SELECTOR -#endif -} +@dynamic delegate; - (uint16_t)of_bindToAddress: (of_socket_address_t *)address extraType: (int)extraType { void *pool = objc_autoreleasePoolPush(); @@ -277,235 +189,6 @@ objc_autoreleasePoolPop(pool); return port; } - -- (size_t)receiveIntoBuffer: (void *)buffer - length: (size_t)length - sender: (of_socket_address_t *)sender -{ - ssize_t ret; - - if (_socket == INVALID_SOCKET) - @throw [OFNotOpenException exceptionWithObject: self]; - - sender->length = (socklen_t)sizeof(sender->sockaddr); - -#ifndef OF_WINDOWS - if ((ret = recvfrom(_socket, buffer, length, 0, - &sender->sockaddr.sockaddr, &sender->length)) < 0) - @throw [OFReadFailedException - exceptionWithObject: self - requestedLength: length - errNo: of_socket_errno()]; -#else - if (length > INT_MAX) - @throw [OFOutOfRangeException exception]; - - if ((ret = recvfrom(_socket, buffer, (int)length, 0, - &sender->sockaddr.sockaddr, &sender->length)) < 0) - @throw [OFReadFailedException - exceptionWithObject: self - requestedLength: length - errNo: of_socket_errno()]; -#endif - - switch (sender->sockaddr.sockaddr.sa_family) { - case AF_INET: - sender->family = OF_SOCKET_ADDRESS_FAMILY_IPV4; - break; -#ifdef OF_HAVE_IPV6 - case AF_INET6: - sender->family = OF_SOCKET_ADDRESS_FAMILY_IPV6; - break; -#endif - default: - sender->family = OF_SOCKET_ADDRESS_FAMILY_UNKNOWN; - break; - } - - return ret; -} - -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length -{ - [self asyncReceiveIntoBuffer: buffer - length: length - runLoopMode: of_run_loop_mode_default]; -} - -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length - runLoopMode: (of_run_loop_mode_t)runLoopMode -{ - [OFRunLoop of_addAsyncReceiveForUDPSocket: self - buffer: buffer - length: length - mode: runLoopMode -# ifdef OF_HAVE_BLOCKS - block: NULL -# endif - delegate: _delegate]; -} - -#ifdef OF_HAVE_BLOCKS -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length - block: (of_udp_socket_async_receive_block_t)block -{ - [self asyncReceiveIntoBuffer: buffer - length: length - runLoopMode: of_run_loop_mode_default - block: block]; -} - -- (void)asyncReceiveIntoBuffer: (void *)buffer - length: (size_t)length - runLoopMode: (of_run_loop_mode_t)runLoopMode - block: (of_udp_socket_async_receive_block_t)block -{ - [OFRunLoop of_addAsyncReceiveForUDPSocket: self - buffer: buffer - length: length - mode: runLoopMode - block: block - delegate: nil]; -} -#endif - -- (void)sendBuffer: (const void *)buffer - length: (size_t)length - receiver: (const of_socket_address_t *)receiver -{ - if (_socket == INVALID_SOCKET) - @throw [OFNotOpenException exceptionWithObject: self]; - -#ifndef OF_WINDOWS - ssize_t bytesWritten; - - if (length > SSIZE_MAX) - @throw [OFOutOfRangeException exception]; - - if ((bytesWritten = sendto(_socket, (void *)buffer, length, 0, - (struct sockaddr *)&receiver->sockaddr.sockaddr, - receiver->length)) < 0) - @throw [OFWriteFailedException - exceptionWithObject: self - requestedLength: length - bytesWritten: 0 - errNo: of_socket_errno()]; -#else - int bytesWritten; - - if (length > INT_MAX) - @throw [OFOutOfRangeException exception]; - - if ((bytesWritten = sendto(_socket, buffer, (int)length, 0, - &receiver->sockaddr.sockaddr, receiver->length)) < 0) - @throw [OFWriteFailedException - exceptionWithObject: self - requestedLength: length - bytesWritten: 0 - errNo: of_socket_errno()]; -#endif - - if ((size_t)bytesWritten != length) - @throw [OFWriteFailedException exceptionWithObject: self - requestedLength: length - bytesWritten: bytesWritten - errNo: 0]; -} - -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver -{ - [self asyncSendData: data - receiver: receiver - runLoopMode: of_run_loop_mode_default]; -} - -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver - runLoopMode: (of_run_loop_mode_t)runLoopMode -{ - [OFRunLoop of_addAsyncSendForUDPSocket: self - data: data - receiver: receiver - mode: runLoopMode -# ifdef OF_HAVE_BLOCKS - block: NULL -# endif - delegate: _delegate]; -} - -#ifdef OF_HAVE_BLOCKS -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver - block: (of_udp_socket_async_send_data_block_t)block -{ - [self asyncSendData: data - receiver: receiver - runLoopMode: of_run_loop_mode_default - block: block]; -} - -- (void)asyncSendData: (OFData *)data - receiver: (const of_socket_address_t *)receiver - runLoopMode: (of_run_loop_mode_t)runLoopMode - block: (of_udp_socket_async_send_data_block_t)block -{ - [OFRunLoop of_addAsyncSendForUDPSocket: self - data: data - receiver: receiver - mode: runLoopMode - block: block - delegate: nil]; -} -#endif - -- (void)cancelAsyncRequests -{ - [OFRunLoop of_cancelAsyncRequestsForObject: self - mode: of_run_loop_mode_default]; -} - -- (int)fileDescriptorForReading -{ -#ifndef OF_WINDOWS - return _socket; -#else - if (_socket == INVALID_SOCKET) - return -1; - - if (_socket > INT_MAX) - @throw [OFOutOfRangeException exception]; - - return (int)_socket; -#endif -} - -- (int)fileDescriptorForWriting -{ -#ifndef OF_WINDOWS - return _socket; -#else - if (_socket == INVALID_SOCKET) - return -1; - - if (_socket > INT_MAX) - @throw [OFOutOfRangeException exception]; - - return (int)_socket; -#endif -} - -- (void)close -{ - if (_socket == INVALID_SOCKET) - @throw [OFNotOpenException exceptionWithObject: self]; - - closesocket(_socket); - _socket = INVALID_SOCKET; -} @end