-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.d
887 lines (816 loc) · 25.3 KB
/
util.d
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
module util;
import std.file,
std.stdio,
std.string,
std.array,
std.algorithm,
std.conv,
std.path,
std.exception,
std.container,
std.typecons,
std.socket,
std.traits,
core.thread,
std.bitmanip,
std.outbuffer,
std.regex,
std.datetime,
std.format,
std.range,
std.concurrency
;
version(Posix) import core.stdc.config;
version(Windows) import core.sys.windows.windows;
enum MsgType : ubyte {
CMD,
REPLY,
DATA,
}
enum ReplyType : ubyte {
STRING,
DIR_ENTRIES,
ERROR,
DATA_SETUP
}
enum ID = "NFTX";
class DisconnectException : Exception {
this(Address raddr) {
super(to!string(raddr) ~ " disconnected");
}
}
class NetworkErrorException : Exception {
this() {
super("A network error occurred");
}
}
class WrongMsgException : Exception {
this(TypeInfo exp, TypeInfo got) {
super("Expected " ~ to!string(exp) ~
", got " ~ to!string(got));
}
}
enum BUFSIZE = 8 * 1024;
template isMsgType(T) {
enum isMsgType = is(T == Command) || is(T == Reply);
}
struct NetDirEntry {
this(DirEntry e) {
name = e.name;
isDir = e.isDir;
attributes = e.attributes;
}
this(ubyte[] raw) {
isDir = cast(bool)raw[0];
ubyte[uint.sizeof] tmp = raw[1..5];
attributes = bigEndianToNative!uint(tmp);
name = cast(string) raw[5..$];
}
string name;
bool isDir;
uint attributes;
@property uint length() const {
return cast(uint) name.length + 5;
}
ubyte[] opCast() immutable {
auto buf = new OutBuffer;
buf.write(nativeToBigEndian(length));
buf.write(cast(ubyte) isDir);
buf.write(nativeToBigEndian(attributes));
buf.write(name);
return buf.toBytes();
}
int opCmp(ref const NetDirEntry e) const {
return cmp(name, e.name);
}
static NetDirEntry[] splitRawData(ubyte[] data_) {
ubyte[] data = data_;
NetDirEntry[] output;
while(data.length) {
ubyte[uint.sizeof] tmp = data[0..uint.sizeof];
data = data[uint.sizeof..$];
auto s = bigEndianToNative!uint(tmp);
output ~= NetDirEntry(data[0..s]);
data = data[s..$];
}
return output;
}
}
struct Dimensions {
ushort w;
ushort h;
}
version(Posix) {
extern(C) {
struct winsize {
ushort ws_row;
ushort ws_col;
ushort ws_xpixel;
ushort ws_ypixel;
};
int ioctl(int __fd, c_ulong __request, ...);
enum TIOCGWINSZ = 0x5413;
}
auto getTermSize() {
winsize w;
ioctl(0, TIOCGWINSZ, &w);
return Dimensions(w.ws_col, w.ws_row);
}
}
version(Windows) {
auto getTermSize() {
CONSOLE_SCREEN_BUFFER_INFO bi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &bi);
return cast(Dimensions) bi.dwSize;
}
}
static void progressBar(ulong val, ulong total) {
ushort columns = getTermSize().w;
auto width = columns - 9;
auto app = appender!string();
app.reserve(columns);
app.put('[');
auto ratio = val / cast(double)total;
auto size = cast(uint) (ratio * width);
foreach(i; 0..size) {
app.put('=');
}
foreach(j; size..width) {
app.put(' ');
}
formattedWrite(app, "] %d%%", cast(uint) (ratio * 100));
if(app.capacity) {
auto padding = new char[app.capacity-columns-1];
padding[] = ' ';
app.put(padding);
}
write(strip(app.data));
version(Posix) {
write("\n\33[1A\33[2K");
}
version(Windows) {
write("\r");
stdout.flush();
}
}
static void lsPrettyPrint(T)(T entries_) if(is(T == NetDirEntry[]) || is(T == DirIterator)) {
static if(is(T == DirIterator)) {
NetDirEntry[] entries;
foreach(DirEntry e; entries_) {
entries ~= NetDirEntry(e);
}
}
else {
auto entries = entries_;
}
auto columns = getTermSize().w;
auto app = appender!string();
//strip off anything other than the file/dir name
entries = array(map!(delegate (NetDirEntry e) {e.name = baseName(e.name); return e;})(entries));
//get maximum length of entries
auto width = reduce!((a,b) => max(a,cast(int)b.name.length))(0, entries.sort) + 1;
if(width > columns / 2)
width = columns;
uint counter;
foreach(e; entries) {
string pad;
counter++;
if(!(counter % (columns / width))) {
version(Windows){}
else pad = "\n";
}
string name;
ubyte n;
version(Posix) {//colours
if(e.isDir) {//blue directories
name = "\33[01;34m" ~ e.name;
}
else {
if(e.attributes & octal!100) {//green executables
name = "\33[01;32m" ~ e.name;
}
else {
name = "\33[00;m" ~ e.name;
}
}
n = cast(ubyte) (name.length - e.name.length);
}
else name = e.name;
formattedWrite(app,"%-0*s%s", width + n, name, pad);
}
writeln(strip(app.data));
version(Posix) write("\33[00;m");
}
abstract class NFT {
public:
this() {
commands["ls"] = &ls;
commands["pwd"] = &pwd;
commands["cd"] = &cd;
commands["cpfr"] = &cpfr;
commands["cptr"] = &cptr;
commands["du"] = &du;
commands["rm"] = &rm;
commands["mkdir"] = &mkdir_;
localCommands["locls"] = &locls;
localCommands["locpwd"] = &locpwd;
localCommands["locdu"] = &locdu;
localCommands["loccd"] = &loccd;
localCommands["locrm"] = &locrm;
localCommands["locmkdir"] = &locmkdir;
prevDir = dir = getcwd();
status = true;
socks = new SocketSet;
}
void attachControlSocket(Socket sock) {
control = sock;
remAddr = sock.remoteAddress();
}
void attachControlSocket(shared(Socket) sock) {
control = cast(Socket)sock;
remAddr = control.remoteAddress();
}
void close() {
control.shutdown(SocketShutdown.BOTH);
control.close();
}
void success(Msg)() if(isMsgType!Msg) {
static if(is(Msg == Reply)) {
if(replyBuf.length)
replyBuf.removeBack();
}
else static if(is(Msg == Command)) {
if(cmdBuf.length)
cmdBuf.removeBack();
}
}
void connectDataConnection(Address remote) {
dataSock = new TcpSocket;
socks.add(dataSock);
dataSock.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"seconds"(15));
version(Windows) dataSock.blocking = true;
try {
dataSock.connect(remote);
}
catch(SocketOSException e) {
stderr.writeln(e.msg);
}
}
bool errorCheck(Socket[] socks ...) {
auto set = new SocketSet;
foreach(sock; socks) {
set.add(sock);
}
if(Socket.select(null,null,set,0) > 0) {
return true;
}
return false;
}
bool ownerEnd() {
bool lstat;
receiveTimeout(dur!"usecs"(1),
(OwnerTerminated e) {
lstat = true;
},
(Variant any) {
//this stops the message buffer from filling up
}
);
return lstat;
}
void sendFile(ref File file, bool progress = false) {
if(dataSock.isAlive()) {
StopWatch timer;
TickDuration last = TickDuration.from!"seconds"(0);
timer.start();
ulong bytesSent;
foreach(ubyte[] buf; file.byChunk(BUFSIZE)) {
retry:
if(ownerEnd() || errorCheck(control, dataSock)) {
file.close();
status = false;
return;
}
auto bytes = dataSock.send(buf);
if(bytes == Socket.ERROR)
throw new NetworkErrorException;
else if(bytes == 0)
throw new DisconnectException(remAddr);
else if(bytes == buf.length) {
bytesSent += bytes;
if(progress) {
if(cast(core.time.Duration)(timer.peek() - last) > dur!"msecs"(200)) {
progressBar(bytesSent, file.size);
last = timer.peek();
}
}
}
else {//retry incomplete send
buf = buf[bytes..$];
bytesSent += bytes;
goto retry;
}
}
timer.stop();
if(progress) {
version(Windows) writeln();
writeln("File uploaded in: ", timer.peek().msecs, " msecs");
writefln("Average uploaded speed: %.2f KB/s", (file.size/(timer.peek().to!("msecs",double)()/1000)/1024));
}
}
}
void receiveFile(ref File file, ulong size, bool progress = false) {
if(dataSock.isAlive()) {
StopWatch timer;
TickDuration last = TickDuration.from!"seconds"(0);
timer.start();
ulong bytesReceived;
ubyte[BUFSIZE] buf;
socks.reset();
while(bytesReceived < size) {
if(ownerEnd() || errorCheck(control, dataSock)) {
file.close();
status = false;
return;
}
socks.add(control);
socks.add(dataSock);
Socket.select(socks, null, null, dur!"msecs"(100));
if(socks.isSet(control)) {
Reply r = receiveMsg!Reply();
if(r.rt == ReplyType.ERROR) {
stderr.writeln(cast(string) r.reply);
break;
}
replyBuf.insertBack(r);
}
if(socks.isSet(dataSock)) {
auto bytes = dataSock.receive(buf);
if(bytes > 0) {
bytesReceived += bytes;
if(progress) {
if(cast(core.time.Duration)(timer.peek() - last) > dur!"msecs"(200)) {
progressBar(bytesReceived, size);
last = timer.peek();
}
}
file.rawWrite(buf[0..bytes]);
}
else if(bytes == 0)
throw new DisconnectException(remAddr);
else if(bytes == Socket.ERROR)
throw new NetworkErrorException;
else
throw new Exception("Wrong amount of data received");
}
socks.reset();
}
timer.stop();
if(progress) {
version(Windows) writeln();
writeln("File downloaded in: ", timer.peek().msecs, " msecs");
writefln("Average download speed: %.2f KB/s", (size/(timer.peek().to!("msecs",double)()/1000)/1024));
}
if(size != file.size) {
throw new Exception("File size doesn't match");
}
}
file.flush();
file.close();
}
void sendMsg(Msg)(Msg msg) if(isMsgType!Msg) {
auto bytes = control.send(cast(ubyte[]) ID ~ cast(const(void)[]) msg);
if(bytes == msg.length + ID.length) {
success!Msg();
return;
}
else if(bytes == 0)
throw new DisconnectException(remAddr);
else if(bytes == Socket.ERROR)
throw new NetworkErrorException;
else
throw new Exception("Wrong amount of data sent");
}
Msg receiveMsg(Msg)() if(isMsgType!Msg) {
static if(is(Msg == Reply)) {
if(replyBuf.length) {
return replyBuf.removeAny();
}
}
//first 9 bytes should be ID (4 bytes) + size of data (4 bytes) + msg type (1 byte)
ubyte[9] buf_;
auto bytes = control.receive(buf_);
if(bytes == 0) {
throw new DisconnectException(remAddr);
}
else if(bytes == Socket.ERROR) {
throw new NetworkErrorException;
}
enforceEx!Exception(buf_[].startsWith(ID), "Not an NFT message");
auto buf = buf_[4..$];
if(bytes == buf.length + ID.length) {
static if(is(Msg == Command)) {
if(buf[int.sizeof] != MsgType.CMD) throw new WrongMsgException(typeid(Command),typeid(Reply));
}
else {
if(buf[int.sizeof] != MsgType.REPLY) throw new WrongMsgException(typeid(Reply),typeid(Command));
}
ubyte[uint.sizeof] t1 = buf[0..uint.sizeof];
uint msgSize = bigEndianToNative!uint(t1);
auto buffer = new ubyte[msgSize-uint.sizeof-1]; //dynamic array of rest
bytes = control.receive(buffer);
if(bytes == msgSize-int.sizeof-1) {
return Msg(buf[int.sizeof] ~ buffer);
}
}
throw new Exception("Wrong amount of data received");
}
auto remoteAddress() {
return control.remoteAddress();
}
@property {
string[] getCommands() {
string[] tmp;
foreach(k, cmd; commands) {
tmp ~= k;
}
return tmp;
}
}
bool status;
protected:
Array!Command cmdBuf;
Array!Reply replyBuf;
alias bool delegate(string arg) cmd;
alias void delegate(string arg) localCmd;
cmd[string] commands;
localCmd[string] localCommands;
Address remAddr;
Socket control;
Socket dataSock;
SocketSet socks;
private:
//client-side commands
void locls(string arg) {
string dir = ".";
if(arg.length) {
dir = strip(arg);
if(!dir.exists) {
stderr.writeln(dir, ": no such file or directory.");
return;
}
}
lsPrettyPrint(dirEntries(dir, SpanMode.shallow));
}
void loccd(string arg) {
if(arg.length) {
if(arg == "-") {
chdir(prevDir);
}
else if(arg.exists && arg.isDir) {
prevDir = getcwd();
chdir(absolutePath(arg));
}
else {
stderr.writeln(arg, ": no such directory.");
}
}
else {
chdir(dir);
}
}
void locpwd(string arg) {
writeln(getcwd());
}
void locdu(string arg) {
if(arg.length) {
if(arg.exists && arg.isFile) {
writeln(dirEntry(arg).size, " bytes");
return;
}
stderr.writeln(arg, ": not a file");
return;
}
stderr.writeln("locdu requires an argument.");
}
void locrm(string arg) {
if(arg.length) {
try {
if(arg.isDir)
arg.rmdir();
else if(arg.isFile)
arg.remove();
}
catch(FileException e) {
stderr.writeln(e.msg);
}
}
}
void locmkdir(string arg) {
if(arg.length) {
try {
mkdir(arg);
}
catch(FileException e) {
stderr.writeln(e.msg);
}
}
}
//server-side commands
bool ls(string arg) {
auto x = replyBuf.length;
string dir_ = dir;
if(arg.length && arg.exists && arg.isDir) {
dir_ = arg;
}
NetDirEntry[] tmp;
foreach(entry; filter!(a => !a.isSymlink)(dirEntries(dir_, SpanMode.shallow))) {
tmp ~= NetDirEntry(entry);
tmp[$-1].name = baseName(entry.name);
}
if(tmp.length) {
replyBuf.insertBack(Reply(assumeUnique(tmp)));
}
else {
replyBuf.insertBack(Reply("Nothing here"));
}
return replyBuf.length == x+1;
}
bool du(string arg) {
auto x = replyBuf.length;
if(arg.length) {
auto filename = absolutePath(strip(arg), dir);
if(filename.exists && filename.isFile) {
replyBuf.insertBack(Reply(to!string(dirEntry(filename).size) ~ " bytes"));
}
else {
replyBuf.insertBack(Reply(filename ~ ": not a file."));
}
}
else {
replyBuf.insertBack(Reply("du requires an argument.", ReplyType.ERROR));
}
return replyBuf.length == x+1;
}
bool pwd(string arg) {
auto x = replyBuf.length;
replyBuf.insertBack(Reply(absolutePath(dir), ReplyType.STRING));
return replyBuf.length == x+1;
}
bool cd(string arg) {
auto x = replyBuf.length;
if(arg.length) {
auto str = buildNormalizedPath(absolutePath(arg, dir));
if(str.exists && str.isDir) {
dir = str;
replyBuf.insertBack(Reply(str, ReplyType.STRING));
}
else
replyBuf.insertBack(Reply(arg ~ ": no such directory.", ReplyType.ERROR));
}
else {
dir = getcwd();
replyBuf.insertBack(Reply(dir, ReplyType.STRING));
}
return replyBuf.length == x+1;
}
bool rm(string arg) {
auto x = replyBuf.length;
if(arg.length) {
auto name = absolutePath(strip(arg), dir);
try {
if(name.isDir)
name.rmdir();
else if(name.isFile)
name.remove();
replyBuf.insertBack(Reply("Removed " ~ name, ReplyType.STRING));
}
catch(FileException e) {
replyBuf.insertBack(Reply(e.msg, ReplyType.ERROR));
}
}
return replyBuf.length == x+1;
}
bool mkdir_(string arg) {
auto x = replyBuf.length;
if(arg.length) {
auto path = absolutePath(strip(arg), dir);
try {
mkdir(path);
replyBuf.insertBack(Reply("Created " ~ path, ReplyType.STRING));
}
catch(FileException e) {
stderr.writeln(e.msg);
replyBuf.insertBack(Reply(e.msg, ReplyType.ERROR));
}
}
return replyBuf.length == x+1;
}
Socket openDataConnection() {
Socket s = new TcpSocket;
s.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true);
s.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"seconds"(3));
try s.bind(new InternetAddress(InternetAddress.PORT_ANY));
catch(SocketOSException e) {
s.close();
throw e;
}
s.listen(1);
return s;
}
private void sendEx(Exception e) {
replyBuf.insertBack(Reply(e.msg, ReplyType.ERROR));
}
//server to client transfer
bool cpfr(string arg) {
auto x = replyBuf.length;
Reply * reply;
if(arg.length) {
auto filename = absolutePath(arg, dir);
if(filename.exists() && filename.isFile()) {
try {
auto sock = this.openDataConnection();
auto p = sock.localAddress().toPortString();
auto port = parse!ushort(p);
auto f = File(filename,"rb");
auto rb = nativeToBigEndian(port) ~ nativeToBigEndian(f.size());
reply = new Reply(rb, ReplyType.DATA_SETUP);
this.sendMsg(*reply);
while(true) {
try {
dataSock = sock.accept();
dataSock.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"seconds"(15));
version(Windows) dataSock.blocking = true;
break;
}
catch(SocketOSException e) {
}
}
sendFile(f);
reply = new Reply("File successfully sent from server");
}
catch(NetworkErrorException e) {
sendEx(e);
throw e;
}
catch(DisconnectException e) {
sendEx(e);
throw e;
}
catch(Exception e) {
stderr.writeln(e.msg);
sendEx(e);
}
finally {
if(reply) {
replyBuf.insertBack(*reply);
}
dataSock.close();
}
}
else {
replyBuf.insertBack(Reply(arg ~ ": No such file", ReplyType.ERROR));
}
}
else {
replyBuf.insertBack(Reply("Need an argument", ReplyType.ERROR));
}
return replyBuf.length == x+1;
}
//client to server transfer
bool cptr(string arg) {
auto x = replyBuf.length;
Reply * reply;
if(arg.length) {
auto filename = buildNormalizedPath(dir, baseName(arg));
try {
auto sock = this.openDataConnection();
auto p = sock.localAddress().toPortString();
auto port = parse!ushort(p);
auto rb = nativeToBigEndian(port) ~ nativeToBigEndian!ulong(0);
reply = new Reply(rb, ReplyType.DATA_SETUP);
sendMsg(*reply);
while(true) {
try {
dataSock = sock.accept();
dataSock.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"seconds"(15));
version(Windows) dataSock.blocking = true;
break;
}
catch(SocketOSException e) {
}
}
auto rtmp = receiveMsg!Reply();
ubyte[ulong.sizeof] tmp = rtmp.reply;
auto f = File(filename,"wb");
receiveFile(f, bigEndianToNative!ulong(tmp));
reply = new Reply("File successfully received at server");
}
catch(NetworkErrorException e) {
sendEx(e);
throw e;
}
catch(DisconnectException e) {
sendEx(e);
throw e;
}
catch(Exception e) {
stderr.writeln(e.msg);
sendEx(e);
}
finally {
if(reply) {
replyBuf.insertBack(*reply);
}
dataSock.close();
}
}
else {
replyBuf.insertBack(Reply("Need an argument", ReplyType.ERROR));
}
return replyBuf.length == x+1;
}
string dir;
string prevDir;
}
struct Command {
this(string input) {
auto idx = countUntil(input, ' ');
if(idx > 0) {
cmd = input[0..idx];
arg = strip(input[idx..$]);
}
else {
cmd = strip(input);
}
}
this(ubyte[] input) {
//if taking the raw input it should at least be the right type
enforce(input[0] == MsgType.CMD,"Not a CMD");
auto tmp = array(filter!(`a.length > 0`)(std.algorithm.splitter(input[1..$],cast(ubyte)0)));
if(tmp.length) {
cmd = cast(string) tmp[0];
if(tmp.length > 1) {
arg = cast(string) tmp[1];
}
}
else cmd = strip(cast(string)input);
}
@property uint length() {
return cast(uint) (uint.sizeof + 1 + cmd.length + 1 + arg.length);
}
const(void)[] opCast() {
auto buf = new OutBuffer;
buf.reserve(length);
buf.write(nativeToBigEndian(length).dup);
buf.write(cast(ubyte) MsgType.CMD);
buf.write(cmd);
buf.write(new ubyte[1]);
buf.write(arg);
return buf.toBytes();
}
string cmd;
string arg;
}
struct Reply {
this(ubyte[] input) {
enforce(input[0] == MsgType.REPLY,"Not a REPLY");
rt = input[1];
reply = input[2..$];
}
this(ubyte[] input, ubyte rt_) {
rt = rt_;
reply = input;
}
this(string input, ubyte rt_ = ReplyType.STRING) {
rt = rt_;
reply = cast(ubyte[])input;
}
this(immutable(NetDirEntry)[] es) {
rt = ReplyType.DIR_ENTRIES;
foreach(e; es) {
reply ~= cast(ubyte[]) e;
}
}
//copy constructor
this(this) {
reply = reply.dup;
}
@property uint length() {
return cast(uint)(uint.sizeof + reply.length + 2);
}
const(void)[] opCast() {
auto buf = new OutBuffer;
buf.reserve(length);
buf.write(nativeToBigEndian(length).dup);
buf.write(cast(ubyte) MsgType.REPLY);
buf.write(rt);
buf.write(reply);
return buf.toBytes();
}
string[] splitData() {
return cast(string[]) array(filter!(`a.length > 0`)(std.algorithm.splitter(reply,cast(ubyte)0)));
}
ubyte rt;
ubyte[] reply;
}