aboutsummaryrefslogtreecommitdiffstats
path: root/WireGuardNetworkExtension/WireGuardGoWrapper.m
blob: 8852b7bbf84229489d61ff5c2d58df11d2937b00 (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
//
//  WireGuardGoWrapper.m
//  WireGuardNetworkExtension
//
//  Created by Jeroen Leenarts on 21-06-18.
//  Copyright © 2018 Wireguard. All rights reserved.
//

#import "WireGuardGoWrapper.h"

#include "wireguard.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);

@interface WireGuardGoWrapper ()

@property (nonatomic, assign) int handle;
@property (nonatomic, assign) BOOL isClosed;

@end

@implementation WireGuardGoWrapper

- (void) turnOnWithInterfaceName: (NSString *)interfaceName settingsString: (NSString *)settingsString
{
    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));
}

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

@end

static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len)
{
    WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx;
    printf("Reading from instance with ctx %p into buffer %p of length %zu\n", ctx, buf, len);
    sleep(1);
    return wrapper.isClosed ? -1 : 0;
}

static ssize_t do_write(const void *ctx, const unsigned char *buf, size_t len)
{
    WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx;
    printf("Writing from instance with ctx %p into buffer %p of length %zu\n", ctx, buf, len);
    return len;
}