aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuardNetworkExtension/WireGuardGoWrapper.m
blob: 7631365050afc5f6a90f00927b9972a17c375e3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//
//  WireGuardGoWrapper.m
//  WireGuardNetworkExtension
//
//  Created by Jeroen Leenarts on 21-06-18.
//  Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All rights reserved.
//

#include <os/log.h>

#include "wireguard.h"
#import "WireGuardGoWrapper.h"

/// Trampoline function
static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len);
/// Trampoline function
static ssize_t do_write(const void *ctx, const unsigned char *buf, size_t len);
/// Trampoline function
static void do_log(int level, const char *tag, const char *msg);



@interface WireGuardGoWrapper ()

@property (nonatomic, assign) int handle;
@property (nonatomic, assign) BOOL isClosed;
@property (nonatomic, strong) NSMutableArray<NSData *> *packets;
@property (nonatomic, strong) NSMutableArray<NSNumber *> *protocols;
@property (nonatomic, strong) dispatch_queue_t dispatchQueue;

@property (nonatomic, strong) NSCondition *condition;

@end

@implementation WireGuardGoWrapper

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.packets = [[NSMutableArray alloc]initWithCapacity:100];
        self.handle = -1;
        self.configured = false;
        self.condition = [NSCondition new];
        self.dispatchQueue = dispatch_queue_create("manager", NULL);
    }
    return self;
}

- (BOOL) turnOnWithInterfaceName: (NSString *)interfaceName settingsString: (NSString *)settingsString
{
    os_log([WireGuardGoWrapper log], "WireGuard Go Version %{public}s", wgVersion());

    wgSetLogger(do_log);

    const char * ifName = [interfaceName UTF8String];
    const char * settings = [settingsString UTF8String];

    self.handle = wgTurnOn((gostring_t){ .p = ifName, .n = interfaceName.length }, (gostring_t){ .p = settings, .n = settingsString.length }, do_read, do_write, (__bridge void *)(self));

    return self.handle >= 0;
}

- (void) turnOff
{
    self.isClosed = YES;
    self.configured = NO;
    wgTurnOff(self.handle);
    self.handle = -1;
}

- (void) startReadingPackets {
    [self readPackets];
}

- (void) readPackets {
    dispatch_async(self.dispatchQueue, ^{
        if (self.isClosed || self.handle < 0 || !self.configured ) {
            [self readPackets];
            return;
        }

        os_log_debug([WireGuardGoWrapper log], "readPackets - read call - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);

        [self.packetFlow readPacketsWithCompletionHandler:^(NSArray<NSData *> * _Nonnull packets, NSArray<NSNumber *> * _Nonnull protocols) {
            [self.condition lock];
            @synchronized(self.packets) {
                [self.packets addObjectsFromArray:packets];
                [self.protocols addObjectsFromArray:protocols];
            }
            os_log_debug([WireGuardGoWrapper log], "readPackets - signal - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
            [self.condition signal];
            [self.condition unlock];
            [self readPackets];
        }];
    });
}

+ (NSString *)versionWireGuardGo {
    return [NSString stringWithUTF8String:wgVersion()];
}

+ (os_log_t)log {
    static os_log_t subLog = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        subLog = os_log_create("com.wireguard.ios.WireGuard.WireGuardNetworkExtension", "WireGuard-Go");
    });

    return subLog;
}

@end

static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len)
{
    @autoreleasepool {
        os_log_debug([WireGuardGoWrapper log], "do_read - start - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
        WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx;
        if (wrapper.isClosed) return -1;

        if (wrapper.handle < 0 || !wrapper.configured ) {
            os_log_debug([WireGuardGoWrapper log], "do_read - early - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);

            return 0;
        }


        NSData * __block packet = nil;
//        NSNumber *protocol = nil;
        dispatch_sync(wrapper.dispatchQueue, ^{
            [wrapper.condition lock];
            @synchronized(wrapper.packets) {
                if (wrapper.packets.count == 0) {
                    os_log_debug([WireGuardGoWrapper log], "do_read - no packet - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);

                    return;
                }

                packet = [wrapper.packets objectAtIndex:0];
                //    protocol = [wrapper.protocols objectAtIndex:0];
                [wrapper.packets removeObjectAtIndex:0];
                [wrapper.protocols removeObjectAtIndex:0];
            }
        });

        if (packet == nil) {
            os_log_debug([WireGuardGoWrapper log], "do_read - wait - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
            [wrapper.condition wait];
            [wrapper.condition unlock];
            return 0;
        } else {
            [wrapper.condition unlock];
        }

        NSUInteger packetLength = [packet length];
        if (packetLength > len) {
            // The packet will be dropped when we end up here.
            os_log_debug([WireGuardGoWrapper log], "do_read - drop  - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
            return 0;
        }
        memcpy(buf, [packet bytes], packetLength);
        os_log_debug([WireGuardGoWrapper log], "do_read - packet  - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
        return packetLength;
    }
}

static ssize_t do_write(const void *ctx, const unsigned char *buf, size_t len)
{
    @autoreleasepool {
      os_log_debug([WireGuardGoWrapper log], "do_write - start");

        WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx;
        //TODO: determine IPv4 or IPv6 status.
        NSData *packet = [[NSData alloc] initWithBytes:buf length:len];
        [wrapper.packetFlow writePackets:@[packet] withProtocols:@[@AF_INET]];
        return len;
    }
}

static void do_log(int level, const char *tag, const char *msg)
{
    @autoreleasepool {
        // TODO Get some details on the log level and distribute to matching log levels.
        os_log([WireGuardGoWrapper log], "Log level %d for %{public}s: %{public}s", level, tag, msg);
    }
}