-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZilyHeader.cs
132 lines (116 loc) · 3.39 KB
/
ZilyHeader.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
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace SAPTeam.Zily
{
/// <summary>
/// Represents a standard header for zily packets.
/// </summary>
public class ZilyHeader
{
/// <summary>
/// Gets or Sets the packet flag.
/// </summary>
public int Flag { get; set; }
/// <summary>
/// Gets the packet text length.
/// </summary>
public int Length => Buffer.Length;
/// <summary>
/// Gets or Sets the packet text.
/// </summary>
public string Text
{
get
{
return text;
}
set
{
Buffer = value == null ? Array.Empty<byte>() : encryptor.Encrypt(value);
text = value;
}
}
public byte[] Buffer { get; set; }
string text;
IEncryption encryptor;
/// <summary>
/// Initializes a new instance of the <see cref="ZilyHeader"/>.
/// </summary>
/// <param name="flag">
/// The packet flag.
/// </param>
/// <param name="text">
/// The packet text.
/// </param>
public ZilyHeader(IEncryption encryptor, int flag, string text = null)
{
this.encryptor = encryptor;
Flag = flag;
Text = text;
}
public ZilyHeader(int flag, byte[] buffer, string text = null)
{
Flag = flag;
Buffer = buffer;
this.text = text;
encryptor = Encryption.None;
}
/// <summary>
/// Parses and creates a new instance of the <see cref="ZilyHeader"/>.
/// </summary>
/// <param name="stream">
/// The zily connection stream.
/// </param>
/// <returns>
/// A new instance of the <see cref="ZilyHeader"/>.
/// </returns>
public static ZilyHeader Read(IEncryption encryptor, Stream stream)
{
int flag;
string text = null;
while (true)
{
int data = stream.ReadByte();
if (data != -1)
{
flag = data;
break;
}
}
int length = Math.Max(0, (stream.ReadByte() * 256) + stream.ReadByte());
byte[] buffer = new byte[length];
if (length > 0)
{
stream.Read(buffer, 0, length);
if (encryptor != Encryption.None)
{
text = encryptor.Decrypt(buffer);
}
}
return new ZilyHeader(flag, buffer, text);
}
/// <summary>
/// Converts the header data to byte array.
/// </summary>
/// <returns>
/// An array contains the flag, length and encoded text.
/// </returns>
/// <exception cref="ArgumentException"></exception>
public virtual byte[] ToByteArray()
{
if (Length > ushort.MaxValue)
{
throw new ArgumentException("Length is too long.");
}
return new byte[]
{
(byte)Flag,
(byte)(Length / 256),
(byte)(Length & 255)
}.Concat(Buffer)
.ToArray();
}
}
}