mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
add Android support (#609)
### Motivation: make swift-nio compatible with Android, and pass all test in Android. ### Modifications: * add missed `ifaddrs` implementation * add missed thread related functions - `CNIOLinux_pthread_getname_np`, `CNIOLinux_pthread_setaffinity_np` and `CNIOLinux_pthread_getaffinity_np` * fix types incositency between Linux and Android, e.g. `Epoll.swift` class * make bytes counter explicitely 64bits to avoid overflow on 32bit, in `PendingWritesManager.swift` and `PendingDatagramWritesState.swift` * fix issue with Unix domain socket, first byte need to be zero in Android * several incosistency fixes between Linux and Android api. ### Result: now swift-nio works on Android. All tests passed!
This commit is contained in:
1 parent
81e97329f3
commit
a59293cbcd
25 files changed
+556
-73
No files matched your search
@@ -68,3 +68,11 @@ This product contains "sha1.c" and "sha1.h" from FreeBSD (Copyright (C) 1995, 19
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
* HOMEPAGE:
|
||||
* https://github.com/freebsd/freebsd/tree/master/sys/crypto
|
||||
|
||||
---
|
||||
This product contains "ifaddrs-android.c" and "ifaddrs-android.h" from dxr.mozilla.org. Webrtc is the owner, but we use edited version from mozilla repo (Copyright (c) 2011, The WebRTC project authors. All rights reserved)
|
||||
|
||||
* LICENSE (BSD):
|
||||
* https://webrtc.googlesource.com/src/+/master/LICENSE
|
||||
* HOMEPAGE:
|
||||
* https://webrtc.googlesource.com/
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
Copyright (c) 2011, The WebRTC project authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include "ifaddrs-android.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/utsname.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <net/if.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <linux/netlink.h>
|
||||
#include <linux/rtnetlink.h>
|
||||
|
||||
struct netlinkrequest {
|
||||
struct nlmsghdr header;
|
||||
struct ifaddrmsg msg;
|
||||
};
|
||||
|
||||
static const int kMaxReadSize = 4096;
|
||||
|
||||
static int set_ifname(struct ifaddrs* ifaddr, int interface) {
|
||||
char buf[IFNAMSIZ] = {0};
|
||||
char* name = if_indextoname(interface, buf);
|
||||
if (name == NULL) {
|
||||
return -1;
|
||||
}
|
||||
ifaddr->ifa_name = malloc(strlen(name) + 1);
|
||||
strncpy(ifaddr->ifa_name, name, strlen(name) + 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int set_flags(struct ifaddrs* ifaddr) {
|
||||
int fd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (fd == -1) {
|
||||
return -1;
|
||||
}
|
||||
struct ifreq ifr;
|
||||
memset(&ifr, 0, sizeof(ifr));
|
||||
strncpy(ifr.ifr_name, ifaddr->ifa_name, IFNAMSIZ - 1);
|
||||
int rc = ioctl(fd, SIOCGIFFLAGS, &ifr);
|
||||
close(fd);
|
||||
if (rc == -1) {
|
||||
return -1;
|
||||
}
|
||||
ifaddr->ifa_flags = ifr.ifr_flags;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int set_addresses(struct ifaddrs* ifaddr, struct ifaddrmsg* msg, void* data,
|
||||
size_t len) {
|
||||
if (msg->ifa_family == AF_INET) {
|
||||
struct sockaddr_in* sa = malloc(sizeof(struct sockaddr_in));
|
||||
memset(sa, 0, sizeof(struct sockaddr_in));
|
||||
sa->sin_family = AF_INET;
|
||||
memcpy(&sa->sin_addr, data, len);
|
||||
ifaddr->ifa_addr = (struct sockaddr*)sa;
|
||||
} else if (msg->ifa_family == AF_INET6) {
|
||||
struct sockaddr_in6* sa = malloc(sizeof(struct sockaddr_in6));
|
||||
memset(sa, 0, sizeof(struct sockaddr_in6));
|
||||
sa->sin6_family = AF_INET6;
|
||||
sa->sin6_scope_id = msg->ifa_index;
|
||||
memcpy(&sa->sin6_addr, data, len);
|
||||
ifaddr->ifa_addr = (struct sockaddr*)sa;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int make_prefixes(struct ifaddrs* ifaddr, int family, int prefixlen) {
|
||||
char* prefix = NULL;
|
||||
if (family == AF_INET) {
|
||||
struct sockaddr_in* mask = malloc(sizeof(struct sockaddr_in));
|
||||
memset(mask, 0, sizeof(struct sockaddr_in));
|
||||
mask->sin_family = AF_INET;
|
||||
memset(&mask->sin_addr, 0, sizeof(struct in_addr));
|
||||
ifaddr->ifa_netmask = (struct sockaddr*)mask;
|
||||
if (prefixlen > 32) {
|
||||
prefixlen = 32;
|
||||
}
|
||||
prefix = (char*)&mask->sin_addr;
|
||||
} else if (family == AF_INET6) {
|
||||
struct sockaddr_in6* mask = malloc(sizeof(struct sockaddr_in6));
|
||||
memset(mask, 0, sizeof(struct sockaddr_in6));
|
||||
mask->sin6_family = AF_INET6;
|
||||
memset(&mask->sin6_addr, 0, sizeof(struct in6_addr));
|
||||
ifaddr->ifa_netmask = (struct sockaddr*)mask;
|
||||
if (prefixlen > 128) {
|
||||
prefixlen = 128;
|
||||
}
|
||||
prefix = (char*)&mask->sin6_addr;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
for (int i = 0; i < (prefixlen / 8); i++) {
|
||||
*prefix++ = 0xFF;
|
||||
}
|
||||
char remainder = 0xff;
|
||||
remainder <<= (8 - prefixlen % 8);
|
||||
*prefix = remainder;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int populate_ifaddrs(struct ifaddrs* ifaddr, struct ifaddrmsg* msg, void* bytes,
|
||||
size_t len) {
|
||||
if (set_ifname(ifaddr, msg->ifa_index) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (set_flags(ifaddr) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (set_addresses(ifaddr, msg, bytes, len) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (make_prefixes(ifaddr, msg->ifa_family, msg->ifa_prefixlen) != 0) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int android_getifaddrs(struct ifaddrs** result) {
|
||||
int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
|
||||
if (fd < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct netlinkrequest ifaddr_request;
|
||||
memset(&ifaddr_request, 0, sizeof(ifaddr_request));
|
||||
ifaddr_request.header.nlmsg_flags = NLM_F_ROOT | NLM_F_REQUEST;
|
||||
ifaddr_request.header.nlmsg_type = RTM_GETADDR;
|
||||
ifaddr_request.header.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
|
||||
|
||||
ssize_t count = send(fd, &ifaddr_request, ifaddr_request.header.nlmsg_len, 0);
|
||||
if ((size_t)count != ifaddr_request.header.nlmsg_len) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
struct ifaddrs* start = NULL;
|
||||
struct ifaddrs* current = NULL;
|
||||
char buf[kMaxReadSize];
|
||||
ssize_t amount_read = recv(fd, &buf, kMaxReadSize, 0);
|
||||
while (amount_read > 0) {
|
||||
struct nlmsghdr* header = (struct nlmsghdr*)&buf[0];
|
||||
size_t header_size = (size_t)amount_read;
|
||||
for ( ; NLMSG_OK(header, header_size);
|
||||
header = NLMSG_NEXT(header, header_size)) {
|
||||
switch (header->nlmsg_type) {
|
||||
case NLMSG_DONE:
|
||||
/* Success. Return. */
|
||||
*result = start;
|
||||
close(fd);
|
||||
return 0;
|
||||
case NLMSG_ERROR:
|
||||
close(fd);
|
||||
android_freeifaddrs(start);
|
||||
return -1;
|
||||
case RTM_NEWADDR: {
|
||||
struct ifaddrmsg* address_msg =
|
||||
(struct ifaddrmsg*)NLMSG_DATA(header);
|
||||
struct rtattr* rta = IFA_RTA(address_msg);
|
||||
ssize_t payload_len = IFA_PAYLOAD(header);
|
||||
while (RTA_OK(rta, payload_len)) {
|
||||
if (rta->rta_type == IFA_ADDRESS) {
|
||||
int family = address_msg->ifa_family;
|
||||
if (family == AF_INET || family == AF_INET6) {
|
||||
struct ifaddrs* newest = malloc(sizeof(struct ifaddrs));
|
||||
memset(newest, 0, sizeof(struct ifaddrs));
|
||||
if (current) {
|
||||
current->ifa_next = newest;
|
||||
} else {
|
||||
start = newest;
|
||||
}
|
||||
if (populate_ifaddrs(newest, address_msg, RTA_DATA(rta),
|
||||
RTA_PAYLOAD(rta)) != 0) {
|
||||
android_freeifaddrs(start);
|
||||
*result = NULL;
|
||||
return -1;
|
||||
}
|
||||
current = newest;
|
||||
}
|
||||
}
|
||||
rta = RTA_NEXT(rta, payload_len);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
amount_read = recv(fd, &buf, kMaxReadSize, 0);
|
||||
}
|
||||
close(fd);
|
||||
android_freeifaddrs(start);
|
||||
return -1;
|
||||
}
|
||||
|
||||
void android_freeifaddrs(struct ifaddrs* addrs) {
|
||||
struct ifaddrs* last = NULL;
|
||||
struct ifaddrs* cursor = addrs;
|
||||
while (cursor) {
|
||||
free(cursor->ifa_name);
|
||||
free(cursor->ifa_addr);
|
||||
free(cursor->ifa_netmask);
|
||||
last = cursor;
|
||||
cursor = cursor->ifa_next;
|
||||
free(last);
|
||||
}
|
||||
}
|
||||
|
||||
#endif /* defined(ANDROID) */
|
||||
@@ -23,6 +23,10 @@
|
||||
#include <sched.h>
|
||||
#include <errno.h>
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <pthread.h>
|
||||
#include "ifaddrs-android.h"
|
||||
#endif
|
||||
|
||||
// Some explanation is required here.
|
||||
//
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#ifdef __ANDROID__
|
||||
/*
|
||||
Copyright (c) 2011, The WebRTC project authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef WEBRTC_BASE_IFADDRS_ANDROID_H_
|
||||
#define WEBRTC_BASE_IFADDRS_ANDROID_H_
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netdb.h>
|
||||
|
||||
/* Implementation of getifaddrs for Android.
|
||||
* Fills out a list of ifaddr structs (see below) which contain information
|
||||
* about every network interface available on the host.
|
||||
* See 'man getifaddrs' on Linux or OS X (nb: it is not a POSIX function). */
|
||||
struct ifaddrs {
|
||||
struct ifaddrs* ifa_next;
|
||||
char* ifa_name;
|
||||
unsigned int ifa_flags;
|
||||
struct sockaddr* ifa_addr;
|
||||
struct sockaddr* ifa_netmask;
|
||||
union {
|
||||
struct sockaddr *ifu_broadaddr;
|
||||
struct sockaddr *ifu_dstaddr;
|
||||
} ifa_ifu;
|
||||
};
|
||||
|
||||
int android_getifaddrs(struct ifaddrs** result);
|
||||
void android_freeifaddrs(struct ifaddrs* addrs);
|
||||
|
||||
#endif /* WEBRTC_BASE_IFADDRS_ANDROID_H_ */
|
||||
#endif
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
#include <c_nio_linux.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/prctl.h>
|
||||
|
||||
_Static_assert(sizeof(CNIOLinux_mmsghdr) == sizeof(struct mmsghdr),
|
||||
"sizes of CNIOLinux_mmsghdr and struct mmsghdr differ");
|
||||
@@ -43,14 +44,52 @@ int CNIOLinux_pthread_setname_np(pthread_t thread, const char *name) {
|
||||
}
|
||||
|
||||
int CNIOLinux_pthread_getname_np(pthread_t thread, char *name, size_t len) {
|
||||
#ifdef __ANDROID__
|
||||
// https://android.googlesource.com/platform/bionic/+/master/libc/bionic/pthread_setname_np.cpp#51
|
||||
if (thread == pthread_self()) {
|
||||
return TEMP_FAILURE_RETRY(prctl(PR_GET_NAME, name)) == -1 ? -1 : 0;
|
||||
}
|
||||
|
||||
char comm_name[64];
|
||||
snprintf(comm_name, sizeof(comm_name), "/proc/self/task/%d/comm", pthread_gettid_np(thread));
|
||||
int fd = TEMP_FAILURE_RETRY(open(comm_name, O_CLOEXEC | O_RDONLY));
|
||||
|
||||
if (fd == -1) return -1;
|
||||
|
||||
ssize_t n = TEMP_FAILURE_RETRY(read(fd, name, len));
|
||||
close(fd);
|
||||
if (n == -1) return -1;
|
||||
|
||||
// The kernel adds a trailing '\n' to the /proc file,
|
||||
// so this is actually the normal case for short names.
|
||||
if (n > 0 && name[n - 1] == '\n') {
|
||||
name[n - 1] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (n >= 0 && len <= SSIZE_MAX && n == (ssize_t)len) return 1;
|
||||
|
||||
name[n] = '\0';
|
||||
return 0;
|
||||
#else
|
||||
return pthread_getname_np(thread, name, len);
|
||||
#endif
|
||||
}
|
||||
|
||||
int CNIOLinux_pthread_setaffinity_np(pthread_t thread, size_t cpusetsize, const cpu_set_t *cpuset) {
|
||||
#ifdef __ANDROID__
|
||||
return sched_setaffinity(pthread_gettid_np(thread), cpusetsize, cpuset);
|
||||
#else
|
||||
return pthread_setaffinity_np(thread, cpusetsize, cpuset);
|
||||
#endif
|
||||
}
|
||||
|
||||
int CNIOLinux_pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t *cpuset) {
|
||||
#ifdef __ANDROID__
|
||||
return sched_getaffinity(pthread_gettid_np(thread), cpusetsize, cpuset);
|
||||
#else
|
||||
return pthread_getaffinity_np(thread, cpusetsize, cpuset);
|
||||
#endif
|
||||
}
|
||||
|
||||
void CNIOLinux_CPU_SET(int cpu, cpu_set_t *set) {
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#!/bin/bash
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftNIO open source project
|
||||
##
|
||||
## Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
set -eu
|
||||
|
||||
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
|
||||
case "$(uname -s)" in
|
||||
Darwin)
|
||||
sed=gsed
|
||||
;;
|
||||
*)
|
||||
sed=sed
|
||||
;;
|
||||
esac
|
||||
|
||||
if ! hash ${sed} 2>/dev/null; then
|
||||
echo "You need sed \"${sed}\" to run this script ..."
|
||||
echo
|
||||
echo "On macOS: brew install gnu-sed"
|
||||
exit 42
|
||||
fi
|
||||
|
||||
# Android ifaddrs
|
||||
for f in ifaddrs-android.c ifaddrs-android.h; do
|
||||
curl -o "${f}" \
|
||||
-Ls "https://hg.mozilla.org/releases/mozilla-beta/raw-file/tip/media/mtransport/third_party/nICEr/src/stun/${f}"
|
||||
done
|
||||
|
||||
mv ifaddrs-android.h include/ifaddrs-android.h
|
||||
"$sed" -i -e 's/#if defined(ANDROID)/#ifdef __ANDROID__/' ifaddrs-android.c
|
||||
"$sed" -i -e '/#include <sys\/socket.h>/a #include <netdb.h> ' include/ifaddrs-android.h
|
||||
"$sed" -i -e '1 i\#ifdef __ANDROID__' include/ifaddrs-android.h
|
||||
"$sed" -i -e '$ i\#endif' include/ifaddrs-android.h
|
||||
"$sed" -i \
|
||||
-e '/struct sockaddr\* ifa_netmask/a union {\nstruct sockaddr *ifu_broadaddr;\nstruct sockaddr *ifu_dstaddr;\n} ifa_ifu;' \
|
||||
include/ifaddrs-android.h
|
||||
@@ -48,6 +48,10 @@
|
||||
#define _CRYPTO_SHA1_H_
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <sys/endian.h>
|
||||
#endif
|
||||
|
||||
struct sha1_ctxt {
|
||||
union {
|
||||
u_int8_t b8[20];
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
/// needed to implement it.
|
||||
///
|
||||
/// This resolver is a single-use object: it can only be used to perform a single host resolution.
|
||||
import CNIOLinux
|
||||
|
||||
internal class GetaddrinfoResolver: Resolver {
|
||||
private let v4Future: EventLoopPromise<[SocketAddress]>
|
||||
private let v6Future: EventLoopPromise<[SocketAddress]>
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
// Created by Cory Benfield on 27/02/2018.
|
||||
//
|
||||
|
||||
import CNIOLinux
|
||||
|
||||
private extension ifaddrs {
|
||||
var dstaddr: UnsafeMutablePointer<sockaddr>? {
|
||||
#if os(Linux)
|
||||
|
||||
+30
-13
@@ -65,16 +65,29 @@ internal enum EventFd {
|
||||
|
||||
internal enum Epoll {
|
||||
public typealias epoll_event = CNIOLinux.epoll_event
|
||||
public static let EPOLL_CTL_ADD = CNIOLinux.EPOLL_CTL_ADD
|
||||
public static let EPOLL_CTL_MOD = CNIOLinux.EPOLL_CTL_MOD
|
||||
public static let EPOLL_CTL_DEL = CNIOLinux.EPOLL_CTL_DEL
|
||||
public static let EPOLLIN = CNIOLinux.EPOLLIN
|
||||
public static let EPOLLOUT = CNIOLinux.EPOLLOUT
|
||||
public static let EPOLLERR = CNIOLinux.EPOLLERR
|
||||
public static let EPOLLRDHUP = CNIOLinux.EPOLLRDHUP
|
||||
public static let EPOLLHUP = CNIOLinux.EPOLLHUP
|
||||
public static let EPOLLET = CNIOLinux.EPOLLET
|
||||
public static let ENOENT = CNIOLinux.ENOENT
|
||||
|
||||
public static let EPOLL_CTL_ADD: CInt = numericCast(CNIOLinux.EPOLL_CTL_ADD)
|
||||
public static let EPOLL_CTL_MOD: CInt = numericCast(CNIOLinux.EPOLL_CTL_MOD)
|
||||
public static let EPOLL_CTL_DEL: CInt = numericCast(CNIOLinux.EPOLL_CTL_DEL)
|
||||
|
||||
#if os(Android)
|
||||
public static let EPOLLIN: CUnsignedInt = numericCast(CNIOLinux.EPOLLIN)
|
||||
public static let EPOLLOUT: CUnsignedInt = numericCast(CNIOLinux.EPOLLOUT)
|
||||
public static let EPOLLERR: CUnsignedInt = numericCast(CNIOLinux.EPOLLERR)
|
||||
public static let EPOLLRDHUP: CUnsignedInt = numericCast(CNIOLinux.EPOLLRDHUP)
|
||||
public static let EPOLLHUP: CUnsignedInt = numericCast(CNIOLinux.EPOLLHUP)
|
||||
public static let EPOLLET: CUnsignedInt = numericCast(CNIOLinux.EPOLLET)
|
||||
#else
|
||||
public static let EPOLLIN: CUnsignedInt = numericCast(CNIOLinux.EPOLLIN.rawValue)
|
||||
public static let EPOLLOUT: CUnsignedInt = numericCast(CNIOLinux.EPOLLOUT.rawValue)
|
||||
public static let EPOLLERR: CUnsignedInt = numericCast(CNIOLinux.EPOLLERR.rawValue)
|
||||
public static let EPOLLRDHUP: CUnsignedInt = numericCast(CNIOLinux.EPOLLRDHUP.rawValue)
|
||||
public static let EPOLLHUP: CUnsignedInt = numericCast(CNIOLinux.EPOLLHUP.rawValue)
|
||||
public static let EPOLLET: CUnsignedInt = numericCast(CNIOLinux.EPOLLET.rawValue)
|
||||
#endif
|
||||
|
||||
public static let ENOENT: CUnsignedInt = numericCast(CNIOLinux.ENOENT)
|
||||
|
||||
|
||||
@inline(never)
|
||||
public static func epoll_create(size: Int32) throws -> Int32 {
|
||||
@@ -99,9 +112,13 @@ internal enum Epoll {
|
||||
}
|
||||
|
||||
internal enum Linux {
|
||||
static let SOCK_CLOEXEC = Int32(bitPattern: Glibc.SOCK_CLOEXEC.rawValue)
|
||||
static let SOCK_NONBLOCK = Int32(bitPattern: Glibc.SOCK_NONBLOCK.rawValue)
|
||||
|
||||
#if os(Android)
|
||||
static let SOCK_CLOEXEC = Glibc.SOCK_CLOEXEC
|
||||
static let SOCK_NONBLOCK = Glibc.SOCK_NONBLOCK
|
||||
#else
|
||||
static let SOCK_CLOEXEC = CInt(bitPattern: Glibc.SOCK_CLOEXEC.rawValue)
|
||||
static let SOCK_NONBLOCK = CInt(bitPattern: Glibc.SOCK_NONBLOCK.rawValue)
|
||||
#endif
|
||||
@inline(never)
|
||||
public static func accept4(descriptor: CInt, addr: UnsafeMutablePointer<sockaddr>, len: UnsafeMutablePointer<socklen_t>, flags: Int32) throws -> CInt? {
|
||||
let result: IOResult<CInt> = try wrapSyscallMayBlock {
|
||||
|
||||
@@ -92,12 +92,12 @@ private func doPendingDatagramWriteVectorOperation(pending: PendingDatagramWrite
|
||||
}
|
||||
|
||||
let toWriteForThisBuffer = p.data.readableBytes
|
||||
toWrite += toWriteForThisBuffer
|
||||
toWrite += numericCast(toWriteForThisBuffer)
|
||||
|
||||
p.data.withUnsafeReadableBytesWithStorageManagement { ptr, storageRef in
|
||||
storageRefs[c] = storageRef.retain()
|
||||
let addressLen = p.copySocketAddress(addresses.baseAddress! + c)
|
||||
iovecs[c] = iovec(iov_base: UnsafeMutableRawPointer(mutating: ptr.baseAddress!), iov_len: toWriteForThisBuffer)
|
||||
iovecs[c] = iovec(iov_base: UnsafeMutableRawPointer(mutating: ptr.baseAddress!), iov_len: numericCast(toWriteForThisBuffer))
|
||||
|
||||
var msg = msghdr(msg_name: addresses.baseAddress! + c,
|
||||
msg_namelen: addressLen,
|
||||
@@ -132,7 +132,7 @@ private struct PendingDatagramWritesState {
|
||||
|
||||
private var pendingWrites = MarkedCircularBuffer<PendingDatagramWrite>(initialRingCapacity: 16)
|
||||
private var chunks: Int = 0
|
||||
public private(set) var bytes: Int = 0
|
||||
public private(set) var bytes: Int64 = 0
|
||||
|
||||
public var nextWrite: PendingDatagramWrite? {
|
||||
return self.pendingWrites.first
|
||||
@@ -141,7 +141,7 @@ private struct PendingDatagramWritesState {
|
||||
/// Subtract `bytes` from the number of outstanding bytes to write.
|
||||
private mutating func subtractOutstanding(bytes: Int) {
|
||||
assert(self.bytes >= bytes, "allegedly written more bytes (\(bytes)) than outstanding (\(self.bytes))")
|
||||
self.bytes -= bytes
|
||||
self.bytes -= numericCast(bytes)
|
||||
}
|
||||
|
||||
/// Indicates that the first outstanding write was written.
|
||||
@@ -177,7 +177,7 @@ private struct PendingDatagramWritesState {
|
||||
public mutating func append(_ chunk: PendingDatagramWrite) {
|
||||
self.pendingWrites.append(chunk)
|
||||
self.chunks += 1
|
||||
self.bytes += chunk.data.readableBytes
|
||||
self.bytes += numericCast(chunk.data.readableBytes)
|
||||
}
|
||||
|
||||
/// Mark the flush checkpoint.
|
||||
@@ -285,7 +285,7 @@ private struct PendingDatagramWritesState {
|
||||
while !self.pendingWrites.isEmpty {
|
||||
let w = self.pendingWrites.removeFirst()
|
||||
self.chunks -= 1
|
||||
self.bytes -= w.data.readableBytes
|
||||
self.bytes -= numericCast(w.data.readableBytes)
|
||||
w.promise.map { promises.append($0) }
|
||||
}
|
||||
|
||||
|
||||
@@ -48,11 +48,11 @@ private func doPendingWriteVectorOperation(pending: PendingStreamWritesState,
|
||||
break loop
|
||||
}
|
||||
let toWriteForThisBuffer = min(Socket.writevLimitBytes, buffer.readableBytes)
|
||||
toWrite += toWriteForThisBuffer
|
||||
toWrite += numericCast(toWriteForThisBuffer)
|
||||
|
||||
buffer.withUnsafeReadableBytesWithStorageManagement { ptr, storageRef in
|
||||
storageRefs[i] = storageRef.retain()
|
||||
iovecs[i] = iovec(iov_base: UnsafeMutableRawPointer(mutating: ptr.baseAddress!), iov_len: toWriteForThisBuffer)
|
||||
iovecs[i] = iovec(iov_base: UnsafeMutableRawPointer(mutating: ptr.baseAddress!), iov_len: numericCast(toWriteForThisBuffer))
|
||||
}
|
||||
numberOfUsedStorageSlots += 1
|
||||
case .fileRegion:
|
||||
@@ -103,7 +103,7 @@ internal enum OverallWriteResult {
|
||||
/// - `failAll` if for some reason all outstanding writes need to be discarded and the corresponding `EventLoopPromise` needs to be failed.
|
||||
private struct PendingStreamWritesState {
|
||||
private var pendingWrites = MarkedCircularBuffer<PendingStreamWrite>(initialRingCapacity: 16)
|
||||
public private(set) var bytes: Int = 0
|
||||
public private(set) var bytes: Int64 = 0
|
||||
|
||||
public var flushedChunks: Int {
|
||||
return self.pendingWrites.markedElementIndex().map { $0 + 1 } ?? 0
|
||||
@@ -112,7 +112,7 @@ private struct PendingStreamWritesState {
|
||||
/// Subtract `bytes` from the number of outstanding bytes to write.
|
||||
private mutating func subtractOutstanding(bytes: Int) {
|
||||
assert(self.bytes >= bytes, "allegedly written more bytes (\(bytes)) than outstanding (\(self.bytes))")
|
||||
self.bytes -= bytes
|
||||
self.bytes -= numericCast(bytes)
|
||||
}
|
||||
|
||||
/// Indicates that the first outstanding write was written in its entirety.
|
||||
@@ -154,9 +154,9 @@ private struct PendingStreamWritesState {
|
||||
self.pendingWrites.append(chunk)
|
||||
switch chunk.data {
|
||||
case .byteBuffer(let buffer):
|
||||
self.bytes += buffer.readableBytes
|
||||
self.bytes += numericCast(buffer.readableBytes)
|
||||
case .fileRegion(let fileRegion):
|
||||
self.bytes += fileRegion.readableBytes
|
||||
self.bytes += numericCast(fileRegion.readableBytes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -200,34 +200,34 @@ extension SelectorEventSet {
|
||||
var epollEventSet: UInt32 {
|
||||
assert(self != ._none)
|
||||
// EPOLLERR | EPOLLHUP is always set unconditionally anyway but it's easier to understand if we explicitly ask.
|
||||
var filter: UInt32 = Epoll.EPOLLERR.rawValue | Epoll.EPOLLHUP.rawValue
|
||||
var filter: UInt32 = Epoll.EPOLLERR | Epoll.EPOLLHUP
|
||||
let epollFilters = EpollFilterSet(selectorEventSet: self)
|
||||
if epollFilters.contains(.input) {
|
||||
filter |= Epoll.EPOLLIN.rawValue
|
||||
filter |= Epoll.EPOLLIN
|
||||
}
|
||||
if epollFilters.contains(.output) {
|
||||
filter |= Epoll.EPOLLOUT.rawValue
|
||||
filter |= Epoll.EPOLLOUT
|
||||
}
|
||||
if epollFilters.contains(.readHangup) {
|
||||
filter |= Epoll.EPOLLRDHUP.rawValue
|
||||
filter |= Epoll.EPOLLRDHUP
|
||||
}
|
||||
assert(filter & Epoll.EPOLLHUP.rawValue != 0) // both of these are reported
|
||||
assert(filter & Epoll.EPOLLERR.rawValue != 0) // always and can't be masked.
|
||||
assert(filter & Epoll.EPOLLHUP != 0) // both of these are reported
|
||||
assert(filter & Epoll.EPOLLERR != 0) // always and can't be masked.
|
||||
return filter
|
||||
}
|
||||
|
||||
fileprivate init(epollEvent: Epoll.epoll_event) {
|
||||
var selectorEventSet: SelectorEventSet = ._none
|
||||
if epollEvent.events & Epoll.EPOLLIN.rawValue != 0 {
|
||||
if epollEvent.events & Epoll.EPOLLIN != 0 {
|
||||
selectorEventSet.formUnion(.read)
|
||||
}
|
||||
if epollEvent.events & Epoll.EPOLLOUT.rawValue != 0 {
|
||||
if epollEvent.events & Epoll.EPOLLOUT != 0 {
|
||||
selectorEventSet.formUnion(.write)
|
||||
}
|
||||
if epollEvent.events & Epoll.EPOLLRDHUP.rawValue != 0 {
|
||||
if epollEvent.events & Epoll.EPOLLRDHUP != 0 {
|
||||
selectorEventSet.formUnion(.readEOF)
|
||||
}
|
||||
if epollEvent.events & Epoll.EPOLLHUP.rawValue != 0 || epollEvent.events & Epoll.EPOLLERR.rawValue != 0 {
|
||||
if epollEvent.events & Epoll.EPOLLHUP != 0 || epollEvent.events & Epoll.EPOLLERR != 0 {
|
||||
selectorEventSet.formUnion(.reset)
|
||||
}
|
||||
self = selectorEventSet
|
||||
@@ -300,7 +300,7 @@ final class Selector<R: Registration> {
|
||||
_ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_ADD, fd: eventfd, event: &ev)
|
||||
|
||||
var timerev = Epoll.epoll_event()
|
||||
timerev.events = Epoll.EPOLLIN.rawValue | Epoll.EPOLLERR.rawValue | Epoll.EPOLLRDHUP.rawValue | Epoll.EPOLLET.rawValue
|
||||
timerev.events = Epoll.EPOLLIN | Epoll.EPOLLERR | Epoll.EPOLLRDHUP | Epoll.EPOLLET
|
||||
timerev.data.fd = timerfd
|
||||
_ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_ADD, fd: timerfd, event: &timerev)
|
||||
#else
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Special `Error` that may be thrown if we fail to create a `SocketAddress`.
|
||||
import CNIOLinux
|
||||
|
||||
public enum SocketAddressError: Error {
|
||||
/// The host is unknown (could not be resolved).
|
||||
case unknown(host: String, port: Int)
|
||||
@@ -188,7 +190,11 @@ public enum SocketAddress: CustomStringConvertible {
|
||||
throw SocketAddressError.unixDomainSocketPathTooLong
|
||||
}
|
||||
|
||||
#if os(Android) // in Android first byte must be zero to use abstract namespace
|
||||
let pathBytes = [0] + Array(unixDomainSocketPath.utf8) + [0]
|
||||
#else
|
||||
let pathBytes = unixDomainSocketPath.utf8 + [0]
|
||||
#endif
|
||||
|
||||
var addr = sockaddr_un()
|
||||
addr.sun_family = sa_family_t(AF_UNIX)
|
||||
@@ -323,8 +329,8 @@ extension SocketAddress {
|
||||
// The easy way to check if this is the case is to just mask off
|
||||
// the address.
|
||||
let v4WireAddress = v4Addr.address.sin_addr.s_addr
|
||||
let mask = in_addr_t(0xF000_0000).bigEndian
|
||||
let subnet = in_addr_t(0xE000_0000).bigEndian
|
||||
let mask = in_addr_t(0xF000_0000 as UInt32).bigEndian
|
||||
let subnet = in_addr_t(0xE000_0000 as UInt32).bigEndian
|
||||
return v4WireAddress & mask == subnet
|
||||
case .v6(let v6Addr):
|
||||
// For IPv6 a multicast address is in the range ff00::/8.
|
||||
|
||||
@@ -30,6 +30,20 @@ internal typealias MMsgHdr = CNIOLinux_mmsghdr
|
||||
let badOS = { fatalError("unsupported OS") }()
|
||||
#endif
|
||||
|
||||
#if os(Android)
|
||||
let INADDR_ANY = UInt32(0) // #define INADDR_ANY ((unsigned long int) 0x00000000)
|
||||
internal typealias sockaddr_storage = __kernel_sockaddr_storage
|
||||
internal typealias in_port_t = UInt16
|
||||
let getifaddrs: @convention(c) (UnsafeMutablePointer<UnsafeMutablePointer<ifaddrs>?>?) -> CInt = android_getifaddrs
|
||||
let freeifaddrs: @convention(c) (UnsafeMutablePointer<ifaddrs>?) -> Void = android_freeifaddrs
|
||||
extension ipv6_mreq { // http://lkml.iu.edu/hypermail/linux/kernel/0106.1/0080.html
|
||||
init (ipv6mr_multiaddr: in6_addr, ipv6mr_interface: UInt32) {
|
||||
self.ipv6mr_multiaddr = ipv6mr_multiaddr
|
||||
self.ipv6mr_ifindex = Int32(bitPattern: ipv6mr_interface)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Declare aliases to share more code and not need to repeat #if #else blocks
|
||||
private let sysClose: @convention(c) (CInt) -> CInt = close
|
||||
private let sysShutdown: @convention(c) (CInt, CInt) -> CInt = shutdown
|
||||
@@ -44,10 +58,21 @@ private let sysConnect: @convention(c) (CInt, UnsafePointer<sockaddr>?, socklen_
|
||||
private let sysOpen: @convention(c) (UnsafePointer<CChar>, CInt) -> CInt = open
|
||||
private let sysOpenWithMode: @convention(c) (UnsafePointer<CChar>, CInt, mode_t) -> CInt = open
|
||||
private let sysWrite: @convention(c) (CInt, UnsafeRawPointer?, CLong) -> CLong = write
|
||||
private let sysWritev: @convention(c) (Int32, UnsafePointer<iovec>?, CInt) -> CLong = writev
|
||||
private let sysRead: @convention(c) (CInt, UnsafeMutableRawPointer?, CLong) -> CLong = read
|
||||
private let sysLseek: @convention(c) (CInt, off_t, CInt) -> off_t = lseek
|
||||
#if os(Android)
|
||||
func sysRecvFrom_wrapper(sockfd: CInt, buf: UnsafeMutableRawPointer, len: CLong, flags: CInt, src_addr: UnsafeMutablePointer<sockaddr>, addrlen: UnsafeMutablePointer<socklen_t>) -> CLong {
|
||||
return recvfrom(sockfd, buf, len, flags, src_addr, addrlen) // src_addr is 'UnsafeMutablePointer', but it need to be 'UnsafePointer'
|
||||
}
|
||||
func sysWritev_wrapper(fd: CInt, iov: UnsafePointer<iovec>?, iovcnt: CInt) -> CLong {
|
||||
return CLong(writev(fd, iov, iovcnt)) // cast 'Int32' to 'CLong'
|
||||
}
|
||||
private let sysRecvFrom = sysRecvFrom_wrapper
|
||||
private let sysWritev = sysWritev_wrapper
|
||||
#else
|
||||
private let sysRecvFrom: @convention(c) (CInt, UnsafeMutableRawPointer?, CLong, CInt, UnsafeMutablePointer<sockaddr>?, UnsafeMutablePointer<socklen_t>?) -> CLong = recvfrom
|
||||
private let sysWritev: @convention(c) (Int32, UnsafePointer<iovec>?, CInt) -> CLong = writev
|
||||
#endif
|
||||
private let sysSendTo: @convention(c) (CInt, UnsafeRawPointer?, CLong, CInt, UnsafePointer<sockaddr>?, socklen_t) -> CLong = sendto
|
||||
private let sysDup: @convention(c) (CInt) -> CInt = dup
|
||||
private let sysGetpeername: @convention(c) (CInt, UnsafeMutablePointer<sockaddr>?, UnsafeMutablePointer<socklen_t>?) -> CInt = getpeername
|
||||
@@ -165,8 +190,14 @@ internal enum Posix {
|
||||
static let SHUT_WR: CInt = CInt(Darwin.SHUT_WR)
|
||||
static let SHUT_RDWR: CInt = CInt(Darwin.SHUT_RDWR)
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
|
||||
#if os(Android)
|
||||
static let SOCK_STREAM: CInt = CInt(Glibc.SOCK_STREAM)
|
||||
static let SOCK_DGRAM: CInt = CInt(Glibc.SOCK_DGRAM)
|
||||
#else
|
||||
static let SOCK_STREAM: CInt = CInt(Glibc.SOCK_STREAM.rawValue)
|
||||
static let SOCK_DGRAM: CInt = CInt(Glibc.SOCK_DGRAM.rawValue)
|
||||
#endif
|
||||
static let IPPROTO_TCP: CInt = CInt(Glibc.IPPROTO_TCP)
|
||||
static let UIO_MAXIOV: Int = Int(Glibc.UIO_MAXIOV)
|
||||
static let SHUT_RD: CInt = CInt(Glibc.SHUT_RD)
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
///
|
||||
/// This is currently the only way to do this in Swift: see
|
||||
/// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
|
||||
import CNIOLinux
|
||||
|
||||
internal func debugOnly(_ body: () -> Void) {
|
||||
assert({ body(); return true }())
|
||||
}
|
||||
|
||||
@@ -17,10 +17,18 @@ private final class ChatHandler: ChannelInboundHandler {
|
||||
public typealias InboundIn = ByteBuffer
|
||||
public typealias OutboundOut = ByteBuffer
|
||||
|
||||
private func printByte(_ byte: UInt8) {
|
||||
#if os(Android)
|
||||
print(Character(UnicodeScalar(byte)), terminator:"")
|
||||
#else
|
||||
fputc(Int32(byte), stdout)
|
||||
#endif
|
||||
}
|
||||
|
||||
public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
|
||||
var buffer = self.unwrapInboundIn(data)
|
||||
while let byte: UInt8 = buffer.readInteger() {
|
||||
fputc(Int32(byte), stdout)
|
||||
printByte(byte)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,6 @@ class HTTPServerClientTest : XCTestCase {
|
||||
typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
private let mode: SendMode
|
||||
private let fileManager = FileManager.default
|
||||
private var files: [String] = Array()
|
||||
private var seenEnd: Bool = false
|
||||
private var sentEnd: Bool = false
|
||||
@@ -97,16 +96,7 @@ class HTTPServerClientTest : XCTestCase {
|
||||
case .byteBuffer:
|
||||
return (.body(.byteBuffer(buffer)), { () in })
|
||||
case .fileRegion:
|
||||
let filePath: String
|
||||
#if os(Linux)
|
||||
filePath = "/tmp/\(UUID().uuidString)"
|
||||
#else
|
||||
if #available(OSX 10.12, *) {
|
||||
filePath = "\(fileManager.temporaryDirectory.path)/\(UUID().uuidString)"
|
||||
} else {
|
||||
filePath = "/tmp/\(UUID().uuidString)"
|
||||
}
|
||||
#endif
|
||||
let filePath: String = "\(temporaryDirectory)/\(UUID().uuidString)"
|
||||
files.append(filePath)
|
||||
|
||||
let content = buffer.getData(at: 0, length: buffer.readableBytes)!
|
||||
@@ -119,12 +109,6 @@ class HTTPServerClientTest : XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
public func handlerRemoved(ctx: ChannelHandlerContext) {
|
||||
for f in files {
|
||||
_ = try? fileManager.removeItem(atPath: f)
|
||||
}
|
||||
}
|
||||
|
||||
public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
|
||||
switch self.unwrapInboundIn(data) {
|
||||
case .head(let req):
|
||||
|
||||
@@ -157,13 +157,13 @@ public class ChannelTests: XCTestCase {
|
||||
for _ in 0..<bufferSize {
|
||||
buffer.write(staticString: "a")
|
||||
}
|
||||
|
||||
|
||||
|
||||
let lotsOfData = Int(Int32.max)
|
||||
var written = 0
|
||||
var written: Int64 = 0
|
||||
while written <= lotsOfData {
|
||||
clientChannel.write(NIOAny(buffer), promise: nil)
|
||||
written += bufferSize
|
||||
written += Int64(bufferSize)
|
||||
}
|
||||
|
||||
XCTAssertNoThrow(try clientChannel.writeAndFlush(NIOAny(buffer)).wait())
|
||||
@@ -286,7 +286,7 @@ public class ChannelTests: XCTestCase {
|
||||
if let expected = expectedVectorWritabilities {
|
||||
if expected.count > multiState {
|
||||
XCTAssertGreaterThan(returns.count, everythingState)
|
||||
XCTAssertEqual(expected[multiState], ptrs.map { $0.iov_len },
|
||||
XCTAssertEqual(expected[multiState], ptrs.map { numericCast($0.iov_len) },
|
||||
"in vector write \(multiState) (overall \(everythingState)), \(expected[multiState]) byte counts expected but \(ptrs.map { $0.iov_len }) actual",
|
||||
file: file, line: line)
|
||||
return returns[everythingState]
|
||||
@@ -697,12 +697,16 @@ public class ChannelTests: XCTestCase {
|
||||
|
||||
/// Test that with a massive buffers (bigger than writev size), we don't offer more than we should to `writev`.
|
||||
func testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk() throws {
|
||||
if MemoryLayout<Int>.size == MemoryLayout<Int32>.size { // skip this test on 32bit system
|
||||
return
|
||||
}
|
||||
|
||||
let el = EmbeddedEventLoop()
|
||||
let alloc = ByteBufferAllocator(hookedMalloc: { _ in UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
|
||||
hookedRealloc: { _, _ in UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
|
||||
hookedFree: { _ in },
|
||||
hookedMemcpy: { _, _, _ in })
|
||||
/* each buffer is half the writev limit */
|
||||
|
||||
let biggerThanWriteV = Socket.writevLimitBytes + 23
|
||||
var buffer = alloc.buffer(capacity: biggerThanWriteV)
|
||||
buffer.moveReaderIndex(to: 0)
|
||||
|
||||
@@ -245,11 +245,11 @@ final class DatagramChannelTests: XCTestCase {
|
||||
let envelope = AddressedEnvelope(remoteAddress: self.secondChannel.localAddress!, data: buffer)
|
||||
|
||||
let lotsOfData = Int(Int32.max)
|
||||
var written = 0
|
||||
var written: Int64 = 0
|
||||
while written <= lotsOfData {
|
||||
self.firstChannel.write(NIOAny(envelope), promise: myPromise)
|
||||
overall = EventLoopFuture<Void>.andAll([overall, myPromise.futureResult], eventLoop: self.firstChannel.eventLoop)
|
||||
written += bufferSize
|
||||
written += Int64(bufferSize)
|
||||
datagrams += 1
|
||||
}
|
||||
}.wait()
|
||||
|
||||
@@ -119,7 +119,7 @@ public class EventLoopTest : XCTestCase {
|
||||
waitForExpectations(timeout: 1) { error in
|
||||
XCTAssertNil(error)
|
||||
XCTAssertEqual(counter.load(), count + 1)
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= initialDelay.nanoseconds + count * delay.nanoseconds)
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= initialDelay.nanoseconds + numericCast(count) * delay.nanoseconds)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ public class IntegerTypesTest: XCTestCase {
|
||||
XCTAssertEqual("72057594037927935", _UInt56.max.description)
|
||||
XCTAssertEqual("12345678901234567", _UInt56(12345678901234567 as UInt64).description)
|
||||
XCTAssertEqual("1", _UInt56(1).description)
|
||||
XCTAssertEqual("36028797018963968", _UInt56(1 << 55).description)
|
||||
XCTAssertEqual("66", _UInt56(66).description)
|
||||
XCTAssertEqual("36028797018963968", _UInt56(UInt64(1) << 55).description)
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,7 @@ class PendingDatagramWritesManagerTests: XCTestCase {
|
||||
if expected.count > multiState {
|
||||
XCTAssertGreaterThan(returns.count, everythingState)
|
||||
XCTAssertEqual(ptrs.map { $0.msg_hdr.msg_iovlen }, Array(repeating: 1, count: ptrs.count), "mustn't write more than one iovec element per datagram", file: file, line: line)
|
||||
XCTAssertEqual(expected[multiState].map { $0.0 }, ptrs.map { $0.msg_hdr.msg_iov.pointee.iov_len },
|
||||
XCTAssertEqual(expected[multiState].map { numericCast($0.0) }, ptrs.map { $0.msg_hdr.msg_iov.pointee.iov_len },
|
||||
"in vector write \(multiState) (overall \(everythingState)), \(expected[multiState]) byte counts expected but \(ptrs.map { $0.msg_hdr.msg_iov.pointee.iov_len }) actual",
|
||||
file: file, line: line)
|
||||
XCTAssertEqual(expected[multiState].map { $0.0 }, ptrs.map { Int($0.msg_len) },
|
||||
@@ -464,13 +464,17 @@ class PendingDatagramWritesManagerTests: XCTestCase {
|
||||
|
||||
/// Test that with a massive buffers (bigger than writev size), we fall back to linear processing.
|
||||
func testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk() throws {
|
||||
if MemoryLayout<Int>.size == MemoryLayout<Int32>.size { // skip this test on 32bit system
|
||||
return
|
||||
}
|
||||
|
||||
let el = EmbeddedEventLoop()
|
||||
let address = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)
|
||||
let alloc = ByteBufferAllocator(hookedMalloc: { _ in return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
|
||||
hookedRealloc: { _, _ in return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
|
||||
hookedFree: { _ in },
|
||||
hookedMemcpy: { _, _, _ in })
|
||||
/* each buffer is half the writev limit */
|
||||
|
||||
let biggerThanWriteV = Socket.writevLimitBytes + 23
|
||||
var buffer = alloc.buffer(capacity: biggerThanWriteV)
|
||||
buffer.moveReaderIndex(to: 0)
|
||||
|
||||
@@ -57,9 +57,24 @@ func withTemporaryFile<T>(content: String? = nil, _ body: (NIO.FileHandle, Strin
|
||||
}
|
||||
return try body(fileHandle, path)
|
||||
}
|
||||
|
||||
var temporaryDirectory: String {
|
||||
get {
|
||||
#if os(Android)
|
||||
return "/data/local/tmp"
|
||||
#elseif os(Linux)
|
||||
return "/tmp"
|
||||
#else
|
||||
if #available(OSX 10.12, *) {
|
||||
return FileManager.default.temporaryDirectory.path
|
||||
} else {
|
||||
return "/tmp"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
func createTemporaryDirectory() -> String {
|
||||
let template = "/tmp/.NIOTests-temp-dir_XXXXXX"
|
||||
let template = "\(temporaryDirectory)/.NIOTests-temp-dir_XXXXXX"
|
||||
|
||||
var templateBytes = template.utf8 + [0]
|
||||
let templateBytesCount = templateBytes.count
|
||||
templateBytes.withUnsafeMutableBufferPointer { ptr in
|
||||
@@ -73,7 +88,7 @@ func createTemporaryDirectory() -> String {
|
||||
}
|
||||
|
||||
func openTemporaryFile() -> (CInt, String) {
|
||||
let template = "/tmp/niotestXXXXXXX"
|
||||
let template = "\(temporaryDirectory)/niotestXXXXXXX"
|
||||
var templateBytes = template.utf8 + [0]
|
||||
let templateBytesCount = templateBytes.count
|
||||
let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ for language in swift-or-c bash dtrace; do
|
||||
matching_files=( -name '*' )
|
||||
case "$language" in
|
||||
swift-or-c)
|
||||
exceptions=( -name c_nio_http_parser.c -o -name c_nio_http_parser.h -o -name cpp_magic.h -o -name Package.swift -o -name c_nio_sha1.h -o -name c_nio_sha1.c)
|
||||
exceptions=( -name c_nio_http_parser.c -o -name c_nio_http_parser.h -o -name cpp_magic.h -o -name Package.swift -o -name c_nio_sha1.h -o -name c_nio_sha1.c -o -name ifaddrs-android.c -o -name ifaddrs-android.h)
|
||||
matching_files=( -name '*.swift' -o -name '*.c' -o -name '*.h' )
|
||||
cat > "$tmp" <<"EOF"
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
Reference in new issue
Block a user