go-bridge: Add context support for wgSetLogger

Cherry picked cda99bf45c3cb95ca56204549689a0ae91ff4813 from jd/loggerCtx with the fix for wgSetLogger signature in the C header file.

Signed-off-by: Andrej Mihajlov <and@mullvad.net>
This commit is contained in:
Jason A. Donenfeld 2020-11-05 17:14:16 +01:00 committed by Andrej Mihajlov
parent ddf8ade9c6
commit 8c057bf928
2 changed files with 9 additions and 7 deletions

View File

@ -7,9 +7,9 @@ package main
// #include <stdlib.h> // #include <stdlib.h>
// #include <sys/types.h> // #include <sys/types.h>
// static void callLogger(void *func, int level, const char *msg) // static void callLogger(void *func, void *ctx, int level, const char *msg)
// { // {
// ((void(*)(int, const char *))func)(level, msg); // ((void(*)(void *, int, const char *))func)(ctx, level, msg);
// } // }
import "C" import "C"
@ -30,6 +30,7 @@ import (
) )
var loggerFunc unsafe.Pointer var loggerFunc unsafe.Pointer
var loggerCtx unsafe.Pointer
var versionString *C.char var versionString *C.char
type CLogger struct { type CLogger struct {
@ -41,7 +42,7 @@ func (l *CLogger) Write(p []byte) (int, error) {
return 0, errors.New("No logger initialized") return 0, errors.New("No logger initialized")
} }
message := C.CString(string(p)) message := C.CString(string(p))
C.callLogger(loggerFunc, l.level, message) C.callLogger(loggerFunc, loggerCtx, l.level, message)
C.free(unsafe.Pointer(message)) C.free(unsafe.Pointer(message))
return len(p), nil return len(p), nil
} }
@ -66,7 +67,7 @@ func init() {
n := runtime.Stack(buf, true) n := runtime.Stack(buf, true)
buf[n] = 0 buf[n] = 0
if uintptr(loggerFunc) != 0 { if uintptr(loggerFunc) != 0 {
C.callLogger(loggerFunc, 0, (*C.char)(unsafe.Pointer(&buf[0]))) C.callLogger(loggerFunc, loggerCtx, 0, (*C.char)(unsafe.Pointer(&buf[0])))
} }
} }
} }
@ -79,7 +80,8 @@ func wgEnableRoaming(enabled bool) {
} }
//export wgSetLogger //export wgSetLogger
func wgSetLogger(loggerFn uintptr) { func wgSetLogger(context, loggerFn uintptr) {
loggerCtx = unsafe.Pointer(context)
loggerFunc = unsafe.Pointer(loggerFn) loggerFunc = unsafe.Pointer(loggerFn)
} }

View File

@ -10,9 +10,9 @@
#include <stdint.h> #include <stdint.h>
#include <stdbool.h> #include <stdbool.h>
typedef void(*logger_fn_t)(int level, const char *msg); typedef void(*logger_fn_t)(void *context, int level, const char *msg);
extern void wgEnableRoaming(bool enabled); extern void wgEnableRoaming(bool enabled);
extern void wgSetLogger(logger_fn_t logger_fn); extern void wgSetLogger(void *context, logger_fn_t logger_fn);
extern int wgTurnOn(const char *settings, int32_t tun_fd); extern int wgTurnOn(const char *settings, int32_t tun_fd);
extern void wgTurnOff(int handle); extern void wgTurnOff(int handle);
extern int64_t wgSetConfig(int handle, const char *settings); extern int64_t wgSetConfig(int handle, const char *settings);