Skip to content

Commit

Permalink
Merge branch 'main' into bug/incoming-check
Browse files Browse the repository at this point in the history
  • Loading branch information
bassosimone authored Feb 13, 2024
2 parents 4bb3416 + f6ce6c2 commit cd2c7cf
Show file tree
Hide file tree
Showing 5 changed files with 282 additions and 179 deletions.
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

0 comments on commit cd2c7cf

Please sign in to comment.