forked from shadowsocks/shadowsocks-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCachedNetworkStream.cs
222 lines (186 loc) · 7.58 KB
/
CachedNetworkStream.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Shadowsocks.Net
{
// cache first packet for duty-chain pattern listener
public class CachedNetworkStream : Stream
{
// 256 byte first packet buffer should enough for 99.999...% situation
// socks5: 0x05 0x....
// http-pac: GET /pac HTTP/1.1
// http-proxy: /[a-z]+ .+ HTTP\/1\.[01]/i
public const int MaxCache = 256;
public Socket Socket { get; private set; }
private readonly Stream s;
private byte[] cache = new byte[MaxCache];
private long cachePtr = 0;
private long readPtr = 0;
public CachedNetworkStream(Socket socket)
{
s = new NetworkStream(socket);
Socket = socket;
}
/// <summary>
/// Only for test purpose
/// </summary>
/// <param name="stream"></param>
public CachedNetworkStream(Stream stream)
{
s = stream;
}
public override bool CanRead => s.CanRead;
// we haven't run out of cache
public override bool CanSeek => cachePtr == readPtr;
public override bool CanWrite => s.CanWrite;
public override long Length => s.Length;
public override long Position { get => readPtr; set => Seek(value, SeekOrigin.Begin); }
public override void Flush()
{
s.Flush();
}
//public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
//{
// var endPtr = buffer.Length + readPtr; // expected ptr after operation
// var uncachedLen = Math.Max(endPtr - cachePtr, 0); // how many data from socket
// var cachedLen = buffer.Length - uncachedLen; // how many data from cache
// var emptyCacheLen = MaxCache - cachePtr; // how many cache remain
// int readLen = 0;
// var cachedMem = buffer[..(int)cachedLen];
// var uncachedMem = buffer[(int)cachedLen..];
// if (cachedLen > 0)
// {
// cache[(int)readPtr..(int)(readPtr + cachedLen)].CopyTo(cachedMem);
// readPtr += cachedLen;
// readLen += (int)cachedLen;
// }
// if (uncachedLen > 0)
// {
// int readStreamLen = await s.ReadAsync(cachedMem, cancellationToken);
// int lengthToCache = (int)Math.Min(emptyCacheLen, readStreamLen); // how many data need to cache
// if (lengthToCache > 0)
// {
// uncachedMem[0..lengthToCache].CopyTo(cache[(int)cachePtr..]);
// cachePtr += lengthToCache;
// }
// readPtr += readStreamLen;
// readLen += readStreamLen;
// }
// return readLen;
//}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int Read(byte[] buffer, int offset, int count)
{
Span<byte> span = buffer.AsSpan(offset, count);
return Read(span);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public override int Read(Span<byte> buffer)
{
// how many data from socket
// r: readPtr, c: cachePtr, e: endPtr
// ptr 0 r c e
// cached ####+++++
// read ++++
// ptr 0 c r e
// cached #####
// read +++++
var endPtr = buffer.Length + readPtr; // expected ptr after operation
var uncachedLen = Math.Max(endPtr - Math.Max(cachePtr, readPtr), 0);
var cachedLen = buffer.Length - uncachedLen; // how many data from cache
var emptyCacheLen = MaxCache - cachePtr; // how many cache remain
int readLen = 0;
Span<byte> cachedSpan = buffer[..(int)cachedLen];
Span<byte> uncachedSpan = buffer[(int)cachedLen..];
if (cachedLen > 0)
{
cache[(int)readPtr..(int)(readPtr + cachedLen)].CopyTo(cachedSpan);
readPtr += cachedLen;
readLen += (int)cachedLen;
}
if (uncachedLen > 0)
{
int readStreamLen = s.Read(uncachedSpan);
// how many data need to cache
int lengthToCache = (int)Math.Min(emptyCacheLen, readStreamLen);
if (lengthToCache > 0)
{
uncachedSpan[0..lengthToCache].ToArray().CopyTo(cache, cachePtr);
cachePtr += lengthToCache;
}
readPtr += readStreamLen;
readLen += readStreamLen;
}
return readLen;
}
/// <summary>
/// Read first block, will never read into non-cache range
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public int ReadFirstBlock(Span<byte> buffer)
{
Seek(0, SeekOrigin.Begin);
int len = Math.Min(MaxCache, buffer.Length);
return Read(buffer[0..len]);
}
/// <summary>
/// Seek position, only support seek to cached range when we haven't read into non-cache range
/// </summary>
/// <param name="offset"></param>
/// <param name="origin">Set it to System.IO.SeekOrigin.Begin, otherwise it will throw System.NotSupportedException</param>
/// <exception cref="IOException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
/// <returns></returns>
public override long Seek(long offset, SeekOrigin origin)
{
if (!CanSeek) throw new NotSupportedException("Non cache data has been read");
if (origin != SeekOrigin.Begin) throw new NotSupportedException("We don't know network stream's length");
if (offset < 0 || offset > cachePtr) throw new NotSupportedException("Can't seek to uncached position");
readPtr = offset;
return Position;
}
/// <summary>
/// Useless
/// </summary>
/// <param name="value"></param>
/// <exception cref="NotSupportedException"></exception>
public override void SetLength(long value)
{
s.SetLength(value);
}
/// <summary>
/// Write to underly stream
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return s.WriteAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Write to underly stream
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
public override void Write(byte[] buffer, int offset, int count)
{
s.Write(buffer, offset, count);
}
protected override void Dispose(bool disposing)
{
s.Dispose();
base.Dispose(disposing);
}
}
}