Repository navigation
Expand file tree
/
Copy pathFileModem.cs
More file actions
374 lines (331 loc) · 15.3 KB
/
Copy pathFileModem.cs
File metadata and controls
374 lines (331 loc) · 15.3 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
using System.Text;
using System.Security.Cryptography;
using System.Linq;
namespace ModemAPI {
public class FileModem : IModem
{
public string CommunicationDirectoryPath { get; private set; }
public string BufferDirectoryPath { get; private set; }
private Dictionary<string, Dictionary<string, string>> IniResolved;
private readonly bool LogsAreEnabled;
private LoggingIntensity EventLoggingIntensity = LoggingIntensity.None;
private long CarryByteLimit = long.MaxValue;
public int MaxReinitializeAttempts { get; set; }
public Address? LocalModemAddress { get; set; }
public LargeMessage? LastDownloadedLargeMessage { get; set; }
public bool IsModemConnected { get; set; }
public FileModem(string communicationPath, string bufferPath)
{
CommunicationDirectoryPath = communicationPath;
BufferDirectoryPath = bufferPath;
IniResolved = IniFileResolver.ParseFile(communicationPath + "carry/config.ini");
if (IniResolved.GetValueOrDefault("COMMUNICATION_PROTOCOL") != null ||
IniResolved.GetValueOrDefault("COMMUNICATION_PROTOCOL")!.GetValueOrDefault("protocol") != "ci_over_tape" ||
IniResolved.GetValueOrDefault("COMMUNICATION_PROTOCOL")!.GetValueOrDefault("allow_transmission") != "true")
{
throw new InvalidDataException();
}
LogsAreEnabled = IniResolved.GetValueOrDefault("LOGGING_EVENTS") != null && IniResolved.GetValueOrDefault("LOGGING_EVENTS")!.GetValueOrDefault("logs_are_enabled") == "true";
string? levelStr = IniResolved.GetValueOrDefault("LOGGING_EVENTS")?.GetValueOrDefault("logging_level");
if (!string.IsNullOrWhiteSpace(levelStr) && Enum.TryParse<LoggingIntensity>(levelStr, true, out var parsed))
{
EventLoggingIntensity = parsed;
}
// read carry limit if provided
string? limitStr = IniResolved.GetValueOrDefault("CARRY_LIMITS")?.GetValueOrDefault("byte_limit");
if (!string.IsNullOrWhiteSpace(limitStr) && long.TryParse(limitStr, out var limit))
{
CarryByteLimit = Math.Max(0, limit);
}
// ensure directories exist
Directory.CreateDirectory(CommunicationDirectoryPath + "carry/");
Directory.CreateDirectory(CommunicationDirectoryPath + "hashes/");
Directory.CreateDirectory(BufferDirectoryPath);
LogMessage("FileModem initialized");
}
public void Dial() {
File.WriteAllText(CommunicationDirectoryPath + $"carry/connection_request_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.hash", "[CONNECTION_REQUEST]");
string hashFile = CommunicationDirectoryPath + $"hashes/hash_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.hash";
byte[] dirHash = ComputeSha512ForDirectory(CommunicationDirectoryPath + "hashes/");
File.WriteAllText(hashFile, ToHex(dirHash), Encoding.UTF8);
TryFlushBufferToCarry();
}
public void Drop(bool carefulMode)
{
LogMessage("FileModem started to disconnect...");
LogMessage("Writing disconnection sequence...");
File.WriteAllText(CommunicationDirectoryPath + $"carry/disconnection_sequence_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.dat", "[DISCONNECTION_SEQUENCE]");
LogMessage("Writing hash...");
string hashFile = CommunicationDirectoryPath + $"hashes/hash_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.hash";
byte[] dirHash = ComputeSha512ForDirectory(CommunicationDirectoryPath + "hashes/");
File.WriteAllText(hashFile, ToHex(dirHash), Encoding.UTF8);
}
public void Transmit(byte[] data, Address address, string queryType, uint connectionId, string? metadata = null, ushort packetSize = 1024, int delay = 100)
{
string ts = DateTime.UtcNow.ToString("yyyyMMdd_HHmmssfff");
string header = $"[TRANSMISSION_HEADER]{address.AddressValue}{queryType}{connectionId}{metadata}";
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
long payloadSize = headerBytes.LongLength + data.LongLength;
bool wroteToCarry = TryWriteToCarry(ts, headerBytes, data, payloadSize);
if (!wroteToCarry)
{
WriteToBuffer(ts, headerBytes, data);
}
TryFlushBufferToCarry();
}
public void LowLevelTransmit(byte[] data, Address address, string qt, uint cid, string? metadata)
{
throw new NotImplementedException();
}
public void Transmit(string data, Address address, string queryType, uint connectionId, string? metadata = null, ushort packetSize = 1024, int delay = 100)
{
string ts = DateTime.UtcNow.ToString("yyyyMMdd_HHmmssfff");
string header = $"[TRANSMISSION_HEADER]{address.AddressValue}{queryType}{connectionId}{metadata}";
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
byte[] payloadBytes = Encoding.UTF8.GetBytes(data);
long payloadSize = headerBytes.LongLength + payloadBytes.LongLength;
bool wroteToCarry = TryWriteToCarry(ts, headerBytes, payloadBytes, payloadSize);
if (!wroteToCarry)
{
WriteToBuffer(ts, headerBytes, payloadBytes);
}
TryFlushBufferToCarry();
}
public void AttachReceiveEvent(Action<DataBlock, Action> onReceive)
{
throw new NotImplementedException();
}
public bool IsAddressSMLA()
{
throw new NotImplementedException();
}
private string GetLogsDirectory()
{
return CommunicationDirectoryPath + "carry/logs/";
}
private string GetTodayLogFile()
{
string dir = GetLogsDirectory();
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
return dir + $"{DateTime.UtcNow:yyyyMMdd}.log";
}
public void LogError(string message)
{
if (!LogsAreEnabled) { return; }
if (EventLoggingIntensity >= LoggingIntensity.Small)
{
AppendLogLine("ERROR", message);
}
}
public void LogWarning(string message)
{
if (!LogsAreEnabled) { return; }
if (EventLoggingIntensity >= LoggingIntensity.Intermediate)
{
AppendLogLine("WARN", message);
}
}
public void LogMessage(string message)
{
if (!LogsAreEnabled) { return; }
if (EventLoggingIntensity >= LoggingIntensity.High)
{
AppendLogLine("INFO", message);
}
}
private void AppendLogLine(string level, string message)
{
string line = $"{DateTime.UtcNow:O} [{level}] {message}{Environment.NewLine}";
File.AppendAllText(GetTodayLogFile(), line, Encoding.UTF8);
}
private bool FlashAvailableAndWritable()
{
try
{
string testDir = CommunicationDirectoryPath + "carry/";
Directory.CreateDirectory(testDir);
string probe = Path.Combine(testDir, $".probe_{Guid.NewGuid():N}");
File.WriteAllText(probe, "probe", Encoding.UTF8);
File.Delete(probe);
return true;
}
catch
{
return false;
}
}
private static long GetDirectorySize(string path)
{
if (!Directory.Exists(path)) return 0L;
return Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Sum(p => new FileInfo(p).Length);
}
private bool TryWriteToCarry(string ts, byte[] headerBytes, byte[] dataBytes, long payloadSize)
{
if (!FlashAvailableAndWritable())
{
LogWarning("Carry not available; will buffer.");
return false;
}
string carryDir = CommunicationDirectoryPath + "carry/";
long currentSize = GetDirectorySize(carryDir);
if (currentSize + payloadSize > CarryByteLimit)
{
LogWarning($"Carry limit exceeded ({currentSize + payloadSize} > {CarryByteLimit}); will buffer.");
return false;
}
string headerPath = Path.Combine(carryDir, $"transmission_header_{ts}.hash");
string payloadPath = Path.Combine(carryDir, $"transmission_sequence_{ts}.dat");
File.WriteAllBytes(headerPath, headerBytes);
File.WriteAllBytes(payloadPath, dataBytes);
LogMessage($"Wrote transmission to carry ({payloadSize} bytes).");
return true;
}
private void WriteToBuffer(string ts, byte[] headerBytes, byte[] dataBytes)
{
Directory.CreateDirectory(BufferDirectoryPath);
string headerPath = Path.Combine(BufferDirectoryPath, $"transmission_header_{ts}.hash");
string payloadPath = Path.Combine(BufferDirectoryPath, $"transmission_sequence_{ts}.dat");
File.WriteAllBytes(headerPath, headerBytes);
File.WriteAllBytes(payloadPath, dataBytes);
LogMessage($"Buffered transmission ({headerBytes.LongLength + dataBytes.LongLength} bytes).");
}
private void TryFlushBufferToCarry()
{
try
{
if (!Directory.Exists(BufferDirectoryPath)) return;
if (!FlashAvailableAndWritable()) return;
string carryDir = CommunicationDirectoryPath + "carry/";
Directory.CreateDirectory(carryDir);
// group header/payload by timestamp prefix to move atomically where possible
var files = Directory.EnumerateFiles(BufferDirectoryPath, "*", SearchOption.TopDirectoryOnly)
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (string file in files)
{
string name = Path.GetFileName(file);
// estimate size impact
long fileLen = new FileInfo(file).Length;
long current = GetDirectorySize(carryDir);
if (current + fileLen > CarryByteLimit)
{
// cannot move further now
break;
}
string dest = Path.Combine(carryDir, name);
File.Move(file, dest, overwrite: true);
}
}
catch (Exception ex)
{
LogWarning($"Buffer flush failed: {ex.Message}");
}
}
private static byte[] ComputeSha512ForDirectory(string rootPath)
{
if (string.IsNullOrWhiteSpace(rootPath))
{
throw new ArgumentNullException(nameof(rootPath));
}
if (!Directory.Exists(rootPath))
{
throw new DirectoryNotFoundException(rootPath);
}
using SHA512 sha = SHA512.Create();
// Stable ordering guarantees deterministic hash
IEnumerable<string> files = Directory.EnumerateFiles(rootPath, "*", SearchOption.AllDirectories)
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase);
bool anyBlock = false;
foreach (string file in files)
{
// Stream file content
using FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 128, FileOptions.SequentialScan);
byte[] buffer = new byte[1024 * 128];
int read;
while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
{
sha.TransformBlock(buffer, 0, read, null, 0);
anyBlock = true;
}
}
if (anyBlock)
{
sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
return sha.Hash ?? Array.Empty<byte>();
}
else
{
// Hash of empty input
return sha.ComputeHash(Array.Empty<byte>());
}
}
private static string ToHex(byte[] bytes)
{
StringBuilder sb = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
public Task GetLargeMessage()
{
throw new NotImplementedException();
}
public Task DeleteLargeMessage(Address transmitter)
{
throw new NotImplementedException();
}
public Task PushLargeMessage(byte[] data, string receiver, uint connectid, string queryType, string? metadata)
{
throw new NotImplementedException();
}
public Task GetLargeMessage(Address transmitter)
{
throw new NotImplementedException();
}
public Task PushLargeMessage(byte[] data, string receiver, uint connectid, string queryType, string metadata, ulong blockId)
{
throw new NotImplementedException();
}
public Task GetLargeMessage(Address tx, Address rx)
{
throw new NotImplementedException();
}
public Task GetLargeMessage(TransmitterReceiverPair txrxpair)
{
throw new NotImplementedException();
}
Task<int> IModem.PushLargeMessage(byte[] data, string receiver, uint connectid, string queryType, string? metadata)
{
throw new NotImplementedException();
}
public Task DeleteLargeMessage(Address tx, Address rx)
{
throw new NotImplementedException();
}
public Task DeleteLargeMessage(TransmitterReceiverPair txrxpair)
{
throw new NotImplementedException();
}
public void AttachReceiveEventNoUnfragment(Action<Packet, Action> onReceive)
{
throw new NotImplementedException();
}
public void Transmit(byte[] data, Address address, string queryType, uint connectionId, string? metadata = null, ushort packetSize = 1024, int delay = 0, ushort ttl = ushort.MaxValue)
{
throw new NotImplementedException();
}
public void Transmit(string data, Address address, string queryType, uint connectionId, string? metadata = null, ushort packetSize = 1024, int delay = 0, ushort ttl = ushort.MaxValue)
{
throw new NotImplementedException();
}
public void LowLevelTransmit(byte[] data, Address address, string queryType, uint connectionId, string? metadata = null, ushort ttl = ushort.MaxValue)
{
throw new NotImplementedException();
}
}
}