From b6d8219244a9791a14605e94724bf62b24da15e9 Mon Sep 17 00:00:00 2001 From: Jeroen Leenarts Date: Sun, 5 Aug 2018 15:58:52 +0200 Subject: Clean up do_read. Signed-off-by: Jason A. Donenfeld --- WireGuardNetworkExtension/WireGuardGoWrapper.m | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'WireGuardNetworkExtension') diff --git a/WireGuardNetworkExtension/WireGuardGoWrapper.m b/WireGuardNetworkExtension/WireGuardGoWrapper.m index 556827c..cd684bf 100644 --- a/WireGuardNetworkExtension/WireGuardGoWrapper.m +++ b/WireGuardNetworkExtension/WireGuardGoWrapper.m @@ -81,6 +81,8 @@ static void do_log(int level, const char *tag, const char *msg); static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len) { WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx; + if (wrapper.isClosed) return -1; + if (wrapper.packets.count == 0) { [wrapper.packetFlow readPacketsWithCompletionHandler:^(NSArray * _Nonnull packets, NSArray * _Nonnull protocols) { @@ -97,11 +99,14 @@ static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len) [wrapper.packets removeObjectAtIndex:0]; [wrapper.protocols removeObjectAtIndex:0]; - len = [packet length]; - buf = (Byte*)malloc(len); - memcpy(buf, [packet bytes], len); + NSUInteger packetLength = [packet length]; + if (packetLength > len) { + // The packet will be dropped when we end up here. + return 0; + } + memcpy(buf, [packet bytes], packetLength); - return wrapper.isClosed ? -1 : 0; + return packetLength; } static ssize_t do_write(const void *ctx, const unsigned char *buf, size_t len) -- cgit v1.2.3-59-g8ed1b