-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathDebugWriter.cs
98 lines (91 loc) · 2.84 KB
/
DebugWriter.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocksTun
{
class DebugWriter
{
public TextWriter Writer { get; set; }
public int LogLevel { get; set; }
public int MaxQueuedMessages = 20;
public readonly StringWriter Status = new StringWriter();
public readonly BlockingQueue<string> Queue = new BlockingQueue<string>();
private const string dateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
public void Log(int level, string message)
{
if (level > LogLevel) return;
var line = DateTime.Now.ToString(dateTimeFormat) + " [" + level + "]: " + message;
if (Writer != null) Writer.WriteLine(line);
if (level < 1)
{
Status.WriteLine(line);
}
else
{
Queue.Enqueue(line);
var count = Queue.Count;
if (count > 0 && count > MaxQueuedMessages)
Queue.Dequeue();
}
}
public void Log(int level, string format, params object[] args)
{
Log(level, string.Format(format, args));
}
public void LogBuffer(string prefix, byte[] buf, int bytesRead)
{
var packetOffset = 0;
var version = buf[packetOffset] >> 4;
if (version == 0x4)
{
var sourceOffset = packetOffset + 12;
var destinationOffset = packetOffset + 16;
var headerLength = (buf[packetOffset] & 0xf) * 4;
var protocol = (ProtocolType)buf[packetOffset + 9];
var source = new IPAddress(BitConverter.ToInt32(buf, sourceOffset) & 0xffffffff);
var destination = new IPAddress(BitConverter.ToInt32(buf, destinationOffset) & 0xffffffff);
switch (protocol)
{
case ProtocolType.Tcp:
case ProtocolType.Udp:
var sourcePort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buf, headerLength + 0)) & 0xffff;
var destinationPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buf, headerLength + 2)) & 0xffff;
Log(5, "{0}: {1}:{3} -> {2}:{4}", protocol, source, destination, sourcePort, destinationPort);
break;
default:
Log(5, "{0}: {1} -> {2}", protocol, source, destination);
break;
}
}
var sb = new StringBuilder();
for (var i = 0; i < bytesRead; i += 0x10)
{
sb.Append(prefix + " " + i.ToString("x8") + " ");
for (var j = i; j < bytesRead && j < i + 0x10; j++)
{
if ((j & 0xf) == 0x8) sb.Append(" ");
sb.Append(buf[j].ToString("x2") + " ");
}
for (var j = i + 0xf; j >= bytesRead; j--)
{
if ((j & 0xf) == 0x8) sb.Append(" ");
sb.Append(" ");
}
sb.Append(" ");
for (var j = i; j < bytesRead && j < i + 0x10; j++)
{
if ((j & 0xf) == 0x8) sb.Append(" ");
var b = (char)buf[j];
if (b < 0x20) b = '.';
sb.Append(b);
}
sb.AppendLine();
}
Log(9, sb.ToString());
}
}
}