-
Notifications
You must be signed in to change notification settings - Fork 0
/
sfn.d
410 lines (364 loc) · 9.34 KB
/
sfn.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
/*
* sfn.d
*
* Copyright 2012 m1kc <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
import std.stdio;
import std.file;
import std.socket;
import std.socketstream;
import std.getopt;
import std.conv;
import std.string;
import std.path;
import std.datetime;
import std.format;
import std.array;
import std.digest.md;
import std.process;
import core.thread;
import std.compiler;
__gshared bool localDone = false;
__gshared bool remoteDone = false;
__gshared SocketStream stream = null;
__gshared Socket listener = null;
__gshared Socket socket = null;
__gshared string[] send;
__gshared string prefix = "";
__gshared bool zenity = false;
__gshared bool disableMD5 = false;
immutable uint windowSize = 1024*64;
immutable ubyte FILE = 0x01;
immutable ubyte DONE = 0x02;
immutable ubyte MD5_WITH_FILE = 0x03;
immutable ubyte FILE_WITH_MD5 = 0x04;
//version = TestBarAndExit;
//version = TestNumbersAndExit;
void main(string[] args)
{
version(TestBarAndExit)
{
long time = currentTime();
int max = int.max/10000;
for (int i=0; i<max; i++) showBar(i, max, time);
return;
}
version(TestNumbersAndExit)
{
int max = int.max;
for (int i=0; i<max; i++) std.stdio.write(numberOfBytes(i), "\r");
writeln;
return;
}
bool server = false;
string connect = null;
ushort port = 3214;
bool help = false;
bool ver = false;
bool noExtIP = false;
getopt(args,
"version|v", &ver,
"help|h", &help,
"listen|l|s", &server,
"connect|c", &connect,
"port|p", &port,
"prefix|f", &prefix,
"no-external-ip|n", &noExtIP,
"zenity|z", &zenity,
"no-integrity-check|e", &disableMD5,
);
send = args[1..$];
if (help) { usage(); return; }
if (ver) { writeln("sfn 1.15" ~ "\nCompiled by: " ~ std.compiler.name); return; }
if ((connect is null) && !server) { usage("You must specify mode."); return; }
if ((connect !is null) && server) { usage("You must specify only one mode."); return; }
if (zenity)
{
string[] names = shell("zenity --file-selection --multiple").chomp().split("|");
foreach(string s; names)
{
writeln("File added: " ~ s);
}
send ~= names;
}
if (server)
{
listener = new TcpSocket();
assert(listener.isAlive);
listener.bind(new InternetAddress(port));
listener.listen(10);
writeln("Waiting for connection...");
if (!noExtIP)
{
Thread ext = new Thread( &extIP );
ext.start();
}
socket = listener.accept();
writeln("Connected: " ~ to!string(socket.remoteAddress()));
stream = new SocketStream(socket);
}
else
{
writeln("Connecting...");
socket = new TcpSocket(new InternetAddress(connect, port));
writeln("Connected.");
stream = new SocketStream(socket);
}
scope(exit)
{
stream.close();
socket.close();
if (listener !is null) listener.close();
}
Thread receiver = new Thread( &receiveFiles );
receiver.start();
Thread sender = new Thread( &sendFiles );
sender.start();
writeln("Started transfer.");
// wait
while(!localDone || !remoteDone) Thread.sleep( dur!("msecs")(100) );
writeln("Transfer complete.");
return;
}
long currentTime()
{
return Clock.currStdTime()/10_000; // hnsecs (hecto-nanoseconds (100 ns)) to millisecs
}
string numberOfBytes(long x)
{
if (x<1024) return to!string(x) ~ " bytes";
auto writer = std.array.appender!string();
if (x<1024*1024) formattedWrite(writer, "%.1f Kb", cast(double)(x)/1024);
else if (x<1024*1024*1024) formattedWrite(writer, "%.1f Mb", cast(double)(x)/(1024*1024));
else formattedWrite(writer, "%.1f Gb", cast(double)(x)/(1024*1024*1024));
return writer.data;
}
version(Windows) // issue #17
{
int getTerminalWidth()
{
return 80;
}
}
else
{
// C extension (ioctl)
extern (C) int getTerminalWidth();
}
void showBar(ulong progress, ulong total, long startTime = -1)
{
string output = " ";
long timeSpent = currentTime()-startTime;
if (timeSpent != 0)
{
output ~= numberOfBytes(progress*1000/timeSpent);
output ~= "/sec ";
}
output ~= numberOfBytes(progress);
output ~= "/";
output ~= numberOfBytes(total);
output ~= "\r";
ulong terminalWidth = getTerminalWidth();
ulong barsCount = terminalWidth
-3 // [], space
-output.length
;
ulong bars = progress*(barsCount+1)/total;
write("[");
for (ulong i=0; i<barsCount; i++) write(i<bars ? "#" : "-");
write("] ");
write(output);
}
void receiveFiles()
{
ubyte b;
while(true)
{
stream.read(b);
if (b == DONE)
{
writeln("Remote done.");
remoteDone = true;
return;
}
else if (b == FILE_WITH_MD5 || b == MD5_WITH_FILE || b == FILE)
{
write("Receiving a file: ");
string filename = to!string(stream.readLine());
write(filename ~ ", ");
ulong size;
stream.read(size);
writeln(size, " bytes");
string md5str = null;
if (b == MD5_WITH_FILE)
{
write("md5: ");
md5str = to!string(stream.readLine());
writeln(md5str);
}
File f = File(prefix ~ filename, "w");
ubyte[] buf = new ubyte[windowSize];
ulong remain = size;
ulong readc;
long time = currentTime();
while(remain > 0)
{
if (remain < windowSize) buf = new ubyte[cast(uint)(remain)];
readc = stream.read(buf);
remain -= readc;
f.rawWrite(buf[0..cast(uint)(readc)]);
showBar(size-remain, size, time);
}
writeln();
writeln("Done.");
f.close();
if (b == FILE_WITH_MD5)
{
write("md5: ");
md5str = to!string(stream.readLine());
writeln(md5str);
}
if (b == FILE_WITH_MD5 || b == MD5_WITH_FILE)
{
writeln("Checking integrity...");
f = File(prefix ~ filename, "r");
MD5 md5;
md5.start();
foreach (ubyte[] b2; f.byChunk(256*1024))
{
md5.put(b2);
}
string md5str2 = toHexString(md5.finish());
md5str2 = md5str2.toLower();
f.close();
writeln( md5str == md5str2 ? "md5 is OK." : "md5 is invalid, file is probably corrupt." );
}
else
{
writeln("Notice: integrity check is impossible, peer uses old version of sfn or have disabled this feature.");
}
}
else
{
writeln("Unexpected byte " ~ to!string(b));
}
}
}
void sendFiles()
{
foreach(string s; send)
{
writeln("Sending a file: " ~ s);
DirEntry d = DirEntry(s);
if (d.isFile())
{
stream.write( disableMD5 ? FILE : FILE_WITH_MD5 );
File f = File(s, "r");
stream.writeString(f.name.split(dirSeparator)[$-1]);
stream.writeString("\n");
stream.write(f.size());
writeln(to!string(f.size()) ~ " bytes");
MD5 md5;
md5.start();
ulong size = f.size();
ulong sent = 0;
long time = currentTime();
foreach (ubyte[] b; f.byChunk(windowSize))
{
md5.put(b);
stream.write(b);
sent += b.length;
showBar(sent, size, time);
}
writeln();
if (!disableMD5)
{
write("md5: ");
string md5str = toHexString(md5.finish());
md5str = md5str.toLower();
writeln(md5str);
stream.writeString(md5str);
stream.writeString("\n");
}
else
{
writeln("Notice: integrity check is disabled.");
}
writeln("Done.");
f.close();
}
else
{
writeln("Error: does not exist or is not a file");
}
}
stream.write(DONE);
localDone = true;
writeln("Local done.");
}
void extIP()
{
// URL: http://tomclaw.com/services/simple/getip.php
Socket sock = new TcpSocket(new InternetAddress("tomclaw.com", 80));
scope(exit) sock.close();
SocketStream ss = new SocketStream(sock);
ss.writeString(
"GET /services/simple/getip.php HTTP/1.0\r\n" ~
"Host: tomclaw.com\r\n" ~
"\r\n"
);
// headers
while(true)
{
auto line = ss.readLine();
if (line.length==0) break;
}
// IP
auto ip = ss.readLine();
writeln("External IP: ", ip);
// reverse DNS lookup
InternetHost ih = new InternetHost();
if (ih.getHostByAddr(ip))
{
writeln("Host: ", ih.name);
foreach (string s; ih.aliases) writeln("Alias: ", s);
}
else
{
writeln("Host: ", "can't determine");
}
}
void usage(string error = null)
{
if (error !is null) writeln(error); else write("sfn - send files over network. ");
write("Usage:
sfn --listen [options] [files to send]
sfn --connect <address> [options] [files to send]
sfn will establish a connection, send all the files, receive all the files from another side and then exit.
-l and -s are aliases for --listen, -c is an alias for --connect.
Options:
--version, -v Show sfn version and exit.
--help, -h Show this text and exit.
--port, -p Use specified port. Defaults to 3214.
--prefix, -f Add prefix to received files' path and name. For example: '/home/user/downloads/', 'sfn-', '/etc/file-'.
--no-external-ip, -n Don't perform external IP detection and reverse DNS lookup.
--zenity, -z Call zenity to select files using standard GTK dialog.
--no-integrity-check, -e Disable integrity check after transfer. For compatibility with older versions of sfn.
");
}