|
| 1 | +// Copyright 2018 Jigsaw Operations LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package shadowsocks |
| 16 | + |
| 17 | +import ( |
| 18 | + "container/list" |
| 19 | + "time" |
| 20 | +) |
| 21 | + |
| 22 | +type CipherCache struct { |
| 23 | + ipCiphers map[string]*list.List |
| 24 | +} |
| 25 | + |
| 26 | +type CachedItem struct { |
| 27 | + itemsList *list.List |
| 28 | + element *list.Element |
| 29 | +} |
| 30 | + |
| 31 | +func (c *CipherCache) GetCiphers(ip string) []*CachedItem { |
| 32 | + cipherList, ok := c.ipCiphers[ip] |
| 33 | + if !ok { |
| 34 | + return []*CachedItem{} |
| 35 | + } |
| 36 | + items := make([]*CachedItem, cipherList.Len()) |
| 37 | + pos := 0 |
| 38 | + for el := cipherList.Front(); el != nil; el = el.Next() { |
| 39 | + items[pos] = &CachedItem{cipherList, el} |
| 40 | + } |
| 41 | + return items |
| 42 | +} |
| 43 | + |
| 44 | +type cipherTime struct { |
| 45 | + CipherID string |
| 46 | + Timestamp time.Time |
| 47 | +} |
| 48 | + |
| 49 | +// WARNING |
| 50 | +// TODO: All of this needs a MUTEX!!!!!!! |
| 51 | +// WARNING |
| 52 | +func (cc *CipherCache) AddCipher(ip string, cipherId string) { |
| 53 | + cipherList, ok := cc.ipCiphers[ip] |
| 54 | + if !ok { |
| 55 | + cipherList = list.New() |
| 56 | + cc.ipCiphers[ip] = cipherList |
| 57 | + } |
| 58 | + cipherList.PushFront(cipherTime{CipherID: cipherId, Timestamp: time.Now()}) |
| 59 | +} |
| 60 | + |
| 61 | +func (cc *CipherCache) ExpireOlderThan(oldestTime time.Time) { |
| 62 | + for key, itemList := range cc.ipCiphers { |
| 63 | + // Remove expired items |
| 64 | + for item := itemList.Back(); item != nil && item.Value.(*cipherTime).Timestamp.Sub(oldestTime) < 0; item = itemList.Back() { |
| 65 | + itemList.Remove(item) |
| 66 | + } |
| 67 | + if itemList.Len() == 0 { |
| 68 | + // TODO: Make this not break the loop |
| 69 | + delete(cc.ipCiphers, key) |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +func (ci *CachedItem) Refresh() { |
| 75 | + ci.element.Value.(*cipherTime).Timestamp = time.Now() |
| 76 | + ci.itemsList.MoveToFront(ci.element) |
| 77 | +} |
| 78 | + |
| 79 | +func (ci *CachedItem) CipherId() string { |
| 80 | + return ci.element.Value.(*cipherTime).CipherID |
| 81 | +} |
0 commit comments