Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: replace minivpn binary #66

Merged
merged 4 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions cmd/minivpn/iface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"fmt"
"net"
)

func getInterfaceByIP(ipAddr string) (*net.Interface, error) {
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}

for _, iface := range interfaces {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}

for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.String() == ipAddr {
return &iface, nil
}
}
}
}

return nil, fmt.Errorf("interface with IP %s not found", ipAddr)
}
79 changes: 79 additions & 0 deletions cmd/minivpn/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package main

import (
"fmt"
"io"
"os"
"sync"
"time"

"github.com/apex/log"
)

// Default handler outputting to stderr.
var Default = NewHandler(os.Stderr)

// start time.
var start = time.Now()

// colors.
const (
none = 0
red = 31
green = 32
yellow = 33
blue = 34
gray = 37
)

// Colors mapping.
var Colors = [...]int{
log.DebugLevel: gray,
log.InfoLevel: blue,
log.WarnLevel: yellow,
log.ErrorLevel: red,
log.FatalLevel: red,
}

// Strings mapping.
var Strings = [...]string{
log.DebugLevel: "DEBUG",
log.InfoLevel: "INFO",
log.WarnLevel: "WARN",
log.ErrorLevel: "ERROR",
log.FatalLevel: "FATAL",
}

// Handler implementation.
type Handler struct {
mu sync.Mutex
Writer io.Writer
}

// New handler.
func NewHandler(w io.Writer) *Handler {
return &Handler{
Writer: w,
}
}

// HandleLog implements log.Handler.
func (h *Handler) HandleLog(e *log.Entry) error {
color := Colors[e.Level]
level := Strings[e.Level]
names := e.Fields.Names()

h.mu.Lock()
defer h.mu.Unlock()

ts := time.Since(start)
fmt.Fprintf(h.Writer, "\033[%dm%6s\033[0m[%10v] %-25s", color, level, ts, e.Message)

for _, name := range names {
fmt.Fprintf(h.Writer, " \033[%dm%s\033[0m=%v", color, name, e.Fields.Get(name))
}

fmt.Fprintln(h.Writer)

return nil
}
Loading
Loading