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

fix lru cache expire #60

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion common/cache/lrucache.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ func (c *LruCache[K, V]) get(key K) *entry[K, V] {
return nil
}

if !c.staleReturn && c.maxAge > 0 && le.Value.expires <= time.Now().Unix() {
if !c.staleReturn && le.Value.expires > 0 && le.Value.expires <= time.Now().Unix() {
c.deleteElement(le)
c.maybeDeleteOldest()

Expand Down
22 changes: 20 additions & 2 deletions common/domain/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@ type Matcher struct {
}

func NewMatcher(domains []string, domainSuffix []string) *Matcher {
domainList := make([]string, 0, len(domains)+len(domainSuffix))
domainList := make([]string, 0, len(domains)+2*len(domainSuffix))
seen := make(map[string]bool, len(domainList))
for _, domain := range domainSuffix {
if seen[domain] {
continue
}
seen[domain] = true
domainList = append(domainList, reverseDomainSuffix(domain))
if domain[0] == '.' {
domainList = append(domainList, reverseDomainSuffix(domain))
} else {
domainList = append(domainList, reverseDomain(domain))
domainList = append(domainList, reverseRootDomainSuffix(domain))
}
}
for _, domain := range domains {
if seen[domain] {
Expand Down Expand Up @@ -134,3 +139,16 @@ func reverseDomainSuffix(domain string) string {
b[l] = prefixLabel
return string(b)
}

func reverseRootDomainSuffix(domain string) string {
l := len(domain)
b := make([]byte, l+2)
for i := 0; i < l; {
r, n := utf8.DecodeRuneInString(domain[i:])
i += n
utf8.EncodeRune(b[l-i:], r)
}
b[l] = '.'
b[l+1] = prefixLabel
return string(b)
}
13 changes: 13 additions & 0 deletions common/json/badjson/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,25 @@ package badjson
import (
"bytes"

"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
)

type JSONArray []any

func (a JSONArray) IsEmpty() bool {
if len(a) == 0 {
return true
}
return common.All(a, func(it any) bool {
if valueInterface, valueMaybeEmpty := it.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
return true
}
return false
})
}

func (a JSONArray) MarshalJSON() ([]byte, error) {
return json.Marshal([]any(a))
}
Expand Down
5 changes: 5 additions & 0 deletions common/json/badjson/empty.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package badjson

type isEmpty interface {
IsEmpty() bool
}
16 changes: 14 additions & 2 deletions common/json/badjson/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,23 @@ type JSONObject struct {
linkedhashmap.Map[string, any]
}

func (m JSONObject) MarshalJSON() ([]byte, error) {
func (m *JSONObject) IsEmpty() bool {
if m.Size() == 0 {
return true
}
return common.All(m.Entries(), func(it collections.MapEntry[string, any]) bool {
if valueInterface, valueMaybeEmpty := it.Value.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
return true
}
return false
})
}

func (m *JSONObject) MarshalJSON() ([]byte, error) {
buffer := new(bytes.Buffer)
buffer.WriteString("{")
items := common.Filter(m.Entries(), func(it collections.MapEntry[string, any]) bool {
if valueObject, valueIsJSONObject := it.Value.(*JSONObject); valueIsJSONObject && valueObject.IsEmpty() {
if valueInterface, valueMaybeEmpty := it.Value.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
return false
}
return true
Expand Down
12 changes: 12 additions & 0 deletions common/winpowrprof/event.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package winpowrprof

const (
EVENT_SUSPEND = iota
EVENT_RESUME
EVENT_RESUME_AUTOMATIC // Because the user is not present, most applications should do nothing.
)

type EventListener interface {
Start() error
Close() error
}
11 changes: 11 additions & 0 deletions common/winpowrprof/event_stub.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//go:build !windows

package winpowrprof

import (
"os"
)

func NewEventListener(callback func(event int)) (EventListener, error) {
return nil, os.ErrInvalid
}
19 changes: 19 additions & 0 deletions common/winpowrprof/event_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package winpowrprof

import (
"runtime"
"testing"

"github.com/stretchr/testify/require"
)

func TestPowerEvents(t *testing.T) {
if runtime.GOOS != "windows" {
t.SkipNow()
}
listener, err := NewEventListener(func(event int) {})
require.NoError(t, err)
require.NotNil(t, listener)
require.NoError(t, listener.Start())
require.NoError(t, listener.Close())
}
83 changes: 83 additions & 0 deletions common/winpowrprof/event_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package winpowrprof

// modify from https://github.com/golang/go/blob/b634f6fdcbebee23b7da709a243f3db217b64776/src/runtime/os_windows.go#L257

import (
"syscall"
"unsafe"

"golang.org/x/sys/windows"
)

var (
modpowerprof = windows.NewLazySystemDLL("powrprof.dll")
procPowerRegisterSuspendResumeNotification = modpowerprof.NewProc("PowerRegisterSuspendResumeNotification")
procPowerUnregisterSuspendResumeNotification = modpowerprof.NewProc("PowerUnregisterSuspendResumeNotification")
)

const (
PBT_APMSUSPEND uint32 = 4
PBT_APMRESUMESUSPEND uint32 = 7
PBT_APMRESUMEAUTOMATIC uint32 = 18
)

const (
_DEVICE_NOTIFY_CALLBACK = 2
)

type _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS struct {
callback uintptr
context uintptr
}

type eventListener struct {
params _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS
handle uintptr
}

func NewEventListener(callback func(event int)) (EventListener, error) {
if err := procPowerRegisterSuspendResumeNotification.Find(); err != nil {
return nil, err // Running on Windows 7, where we don't need it anyway.
}
if err := procPowerUnregisterSuspendResumeNotification.Find(); err != nil {
return nil, err // Running on Windows 7, where we don't need it anyway.
}

var fn interface{} = func(context uintptr, changeType uint32, setting uintptr) uintptr {
switch changeType {
case PBT_APMSUSPEND:
callback(EVENT_SUSPEND)
case PBT_APMRESUMESUSPEND:
callback(EVENT_RESUME)
case PBT_APMRESUMEAUTOMATIC:
callback(EVENT_RESUME_AUTOMATIC)
}
return 0
}
return &eventListener{
params: _DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS{
callback: windows.NewCallback(fn),
},
}, nil
}

func (l *eventListener) Start() error {
_, _, errno := syscall.SyscallN(
procPowerRegisterSuspendResumeNotification.Addr(),
_DEVICE_NOTIFY_CALLBACK,
uintptr(unsafe.Pointer(&l.params)),
uintptr(unsafe.Pointer(&l.handle)),
)
if errno != 0 {
return errno
}
return nil
}

func (l *eventListener) Close() error {
_, _, errno := syscall.SyscallN(procPowerUnregisterSuspendResumeNotification.Addr(), uintptr(unsafe.Pointer(&l.handle)))
if errno != 0 {
return errno
}
return nil
}