forked from Ylianst/MeshCentralRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileViewer.cs
1855 lines (1692 loc) · 81.7 KB
/
FileViewer.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
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2009-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
namespace MeshCentralRouter
{
public partial class FileViewer : Form
{
private MeshCentralServer server = null;
private NodeClass node = null;
private int state = 0;
private RandomNumberGenerator rand = RandomNumberGenerator.Create();
private string randomIdHex = null;
public webSocketClient wc = null;
public Dictionary<string, int> userSessions = null;
public bool sessionIsRecorded = false;
public DirectoryInfo localFolder = null;
public string remoteFolder = null;
public ArrayList remoteFolderList = null;
private static string rndString = getRandomString(12);
private bool skipExistingFiles = false;
private FileDialogMsgForm msgForm = null;
// Stats
public long bytesIn = 0;
public long bytesInCompressed = 0;
public long bytesOut = 0;
public long bytesOutCompressed = 0;
// Upload state
public FileTransferStatusForm transferStatusForm = null;
public bool uploadActive = false;
public bool uploadStop = false;
public int uploadFileArrayPtr = -1;
public ArrayList uploadFileArray;
public Hashtable uploadFileDuplicateArray; // Name --> Size
public DirectoryInfo uploadLocalPath;
public string uploadRemotePath;
public FileStream uploadFileStream = null;
public long uploadFilePtr = 0;
public long uploadFileStartPtr = 0;
public long uploadFileSize = 0;
public DateTime uploadFileStartTime = DateTime.MinValue;
public string uploadFileName = null;
// Download state
public bool downloadActive = false;
public bool downloadStop = false;
public int downloadFileArrayPtr = -1;
public ArrayList downloadFileArray;
public ArrayList downloadFileSizeArray;
public DirectoryInfo downloadLocalPath;
public string downloadRemotePath;
public FileStream downloadFileStream = null;
public long downloadFilePtr = 0;
public long downloadFileSize = 0;
public DateTime downloadFileStartTime = DateTime.MinValue;
public FileViewer(MeshCentralServer server, NodeClass node)
{
InitializeComponent();
Translate.TranslateControl(this);
if (node != null) { this.Text += " - " + node.name; }
this.node = node;
this.server = server;
UpdateStatus();
rightListView.Columns[0].Width = rightListView.Width - rightListView.Columns[1].Width - 22;
// Load the local path from the registry
string lp = Settings.GetRegValue("LocalPath", "");
if ((lp != "") && (Directory.Exists(lp))) { localFolder = new DirectoryInfo(lp); }
}
public bool updateLocalFileView()
{
// Save the list of selected items
List<String> selectedItems = new List<String>();
foreach (ListViewItem l in leftListView.SelectedItems) { selectedItems.Add(l.Text); }
// Refresh the list
leftListView.Items.Clear();
if (localFolder == null)
{
localRootButton.Enabled = false;
localNewFolderButton.Enabled = false;
localDeleteButton.Enabled = false;
try
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
ListViewItem x = new ListViewItem(drive.Name, 0);
x.Tag = drive;
leftListView.Items.Add(x);
}
localUpButton.Enabled = false;
localLabel.Text = Translate.T(Properties.Resources.Local);
mainToolTip.SetToolTip(localLabel, Translate.T(Properties.Resources.Local));
}
catch (Exception) { return false; }
}
else
{
localRootButton.Enabled = true;
localNewFolderButton.Enabled = true;
localDeleteButton.Enabled = false;
try
{
DirectoryInfo[] directories = localFolder.GetDirectories();
foreach (DirectoryInfo directory in directories)
{
ListViewItem x = new ListViewItem(directory.Name, 1);
x.Tag = directory;
leftListView.Items.Add(x);
}
FileInfo[] files = localFolder.GetFiles();
foreach (FileInfo file in files)
{
if (file.Attributes.HasFlag(FileAttributes.Hidden)) continue;
string[] si = new string[2];
si[0] = file.Name;
si[1] = "" + file.Length;
ListViewItem x = new ListViewItem(si, 2);
x.Tag = file;
leftListView.Items.Add(x);
}
localUpButton.Enabled = true;
localLabel.Text = string.Format(Translate.T(Properties.Resources.LocalPlus), localFolder.FullName);
mainToolTip.SetToolTip(localLabel, string.Format(Translate.T(Properties.Resources.LocalPlus), localFolder.FullName));
}
catch (Exception) { return false; }
}
updateTransferButtons();
// Reselect items
foreach (ListViewItem l in leftListView.Items) { l.Selected = selectedItems.Contains(l.Text); }
return true;
}
public class ListViewItemSortClass : IComparer
{
int IComparer.Compare(Object x, Object y)
{
return ((new CaseInsensitiveComparer()).Compare(((ListViewItem)x).SubItems[0].Text, ((ListViewItem)y).SubItems[0].Text));
}
}
private delegate void updateRemoteFileViewHandler();
public void updateRemoteFileView()
{
if (this.InvokeRequired) { this.Invoke(new updateRemoteFileViewHandler(updateRemoteFileView)); return; }
// Save the list of selected items
List<String> selectedItems = new List<String>();
foreach (ListViewItem l in rightListView.SelectedItems) { selectedItems.Add(l.Text); }
rightListView.Items.Clear();
if ((remoteFolder == null) || (remoteFolder == "")) {
remoteLabel.Text = Translate.T(Properties.Resources.Remote);
mainToolTip.SetToolTip(remoteLabel, Translate.T(Properties.Resources.Remote));
} else {
if (node.agentid < 5)
{
remoteLabel.Text = string.Format(Translate.T(Properties.Resources.RemotePlus), remoteFolder.Replace("/", "\\"));
mainToolTip.SetToolTip(remoteLabel, string.Format(Translate.T(Properties.Resources.RemotePlus), remoteFolder.Replace("/", "\\")));
}
else
{
remoteLabel.Text = string.Format(Translate.T(Properties.Resources.RemotePlus), remoteFolder);
mainToolTip.SetToolTip(remoteLabel, string.Format(Translate.T(Properties.Resources.RemotePlus), remoteFolder));
}
}
remoteRefreshButton.Enabled = true;
remoteRootButton.Enabled = !((remoteFolder == null) || (remoteFolder == ""));
remoteUpButton.Enabled = !((remoteFolder == null) || (remoteFolder == ""));
if (node.agentid < 5) {
remoteNewFolderButton.Enabled = !((remoteFolder == null) || (remoteFolder == ""));
remoteDeleteButton.Enabled = remoteZipButton.Enabled = (!((remoteFolder == null) || (remoteFolder == ""))) && (rightListView.SelectedItems.Count > 0);
} else {
remoteNewFolderButton.Enabled = true;
remoteDeleteButton.Enabled = remoteZipButton.Enabled = (rightListView.SelectedItems.Count > 0);
}
if (remoteFolderList != null)
{
ArrayList sortlist = new ArrayList();
// Display all folders
for (int i = 0; i < remoteFolderList.Count; i++)
{
Dictionary<string, object> fileItem = (Dictionary<string, object>)remoteFolderList[i];
int fileIcon = 0;
string fileName = null;
string fileDate = null;
long fileSize = -1;
if (fileItem.ContainsKey("t")) { fileIcon = (int)fileItem["t"]; }
if (fileItem.ContainsKey("n")) { fileName = (string)fileItem["n"]; }
if (fileItem.ContainsKey("d")) { fileDate = (string)fileItem["d"]; }
if (fileItem.ContainsKey("s")) {
if (fileItem["s"].GetType() == typeof(System.Int32)) { fileSize = (int)fileItem["s"]; }
if (fileItem["s"].GetType() == typeof(System.Int64)) { fileSize = (long)fileItem["s"]; }
}
if (fileIcon == 1) {
sortlist.Add(new ListViewItem(fileName, 0)); // Drive
} else if (fileIcon == 2) {
sortlist.Add(new ListViewItem(fileName, 1)); // Folder
}
}
sortlist.Sort(new ListViewItemSortClass());
foreach (ListViewItem l in sortlist) { rightListView.Items.Add(l); }
sortlist.Clear();
// Display all files
for (int i = 0; i < remoteFolderList.Count; i++)
{
Dictionary<string, object> fileItem = (Dictionary<string, object>)remoteFolderList[i];
int fileIcon = 0;
string fileName = null;
string fileDate = null;
long fileSize = -1;
if (fileItem.ContainsKey("t")) { fileIcon = (int)fileItem["t"]; }
if (fileItem.ContainsKey("n")) { fileName = (string)fileItem["n"]; }
if (fileItem.ContainsKey("d")) { fileDate = (string)fileItem["d"]; }
if (fileItem.ContainsKey("s"))
{
if (fileItem["s"].GetType() == typeof(System.Int32)) { fileSize = (int)fileItem["s"]; }
if (fileItem["s"].GetType() == typeof(System.Int64)) { fileSize = (long)fileItem["s"]; }
}
if (fileIcon == 3)
{
// File
string[] si = new string[2];
si[0] = fileName;
si[1] = "" + fileSize;
sortlist.Add(new ListViewItem(si, 2)); // File
}
}
sortlist.Sort(new ListViewItemSortClass());
foreach (ListViewItem l in sortlist) { rightListView.Items.Add(l); }
}
updateTransferButtons();
// Reselect items
foreach (ListViewItem l in rightListView.Items) { l.Selected = selectedItems.Contains(l.Text); }
}
private void Server_onStateChanged(int state)
{
UpdateStatus();
}
private void MainForm_Load(object sender, EventArgs e)
{
updateLocalFileView();
// Restore Window Location
string locationStr = Settings.GetRegValue("filelocation", "");
if (locationStr != null)
{
string[] locationSplit = locationStr.Split(',');
if (locationSplit.Length == 4)
{
try
{
var x = int.Parse(locationSplit[0]);
var y = int.Parse(locationSplit[1]);
var w = int.Parse(locationSplit[2]);
var h = int.Parse(locationSplit[3]);
Point p = new Point(x, y);
if (isPointVisibleOnAScreen(p))
{
Location = p;
if ((w > 50) && (h > 50)) { Size = new Size(w, h); }
}
}
catch (Exception) { }
}
}
}
private void MenuItemExit_Click(object sender, EventArgs e)
{
Close();
}
public void MenuItemConnect_Click(object sender, EventArgs e)
{
if ((wc != null) || (node == null)) return;
byte[] randomid = new byte[10];
rand.GetBytes(randomid);
randomIdHex = BitConverter.ToString(randomid).Replace("-", string.Empty);
state = 1;
string ux = server.wsurl.ToString().Replace("/control.ashx", "/");
int i = ux.IndexOf("?");
if (i >= 0) { ux = ux.Substring(0, i); }
Uri u = new Uri(ux + "meshrelay.ashx?browser=1&p=5&nodeid=" + node.nodeid + "&id=" + randomIdHex + "&auth=" + server.authCookie);
wc = new webSocketClient();
wc.debug = server.debug;
wc.onStateChanged += Wc_onStateChanged;
wc.onBinaryData += Wc_onBinaryData;
wc.onStringData += Wc_onStringData;
wc.TLSCertCheck = webSocketClient.TLSCertificateCheck.Fingerprint;
wc.Start(u, server.wshash, null);
}
private void Wc_onStateChanged(webSocketClient sender, webSocketClient.ConnectionStates wsstate)
{
switch (wsstate)
{
case webSocketClient.ConnectionStates.Disconnected:
{
// Disconnect
state = 0;
wc.Dispose();
wc = null;
break;
}
case webSocketClient.ConnectionStates.Connecting:
{
state = 1;
displayMessage(null);
break;
}
case webSocketClient.ConnectionStates.Connected:
{
// Reset stats
bytesIn = 0;
bytesInCompressed = 0;
bytesOut = 0;
bytesOutCompressed = 0;
state = 2;
string u = "*" + server.wsurl.AbsolutePath.Replace("control.ashx", "meshrelay.ashx") + "?p=5&nodeid=" + node.nodeid + "&id=" + randomIdHex + "&rauth=" + server.rauthCookie;
server.sendCommand("{ \"action\": \"msg\", \"type\": \"tunnel\", \"nodeid\": \"" + node.nodeid + "\", \"value\": \"" + u.ToString() + "\", \"usage\": 5 }");
displayMessage(null);
break;
}
}
UpdateStatus();
updateTransferButtons();
}
private void requestRemoteFolder(string path)
{
// Send LS command
string cmd = "{\"action\":\"ls\",\"reqid\":1,\"path\":\"" + path.Replace("\\","/") + "\"}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
private void requestCreateFolder(string path)
{
// Send MKDIR command
string cmd = "{\"action\":\"mkdir\",\"reqid\":2,\"path\":\"" + path.Replace("\\", "/") + "\"}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
public void requestCancel()
{
string cmd = "{\"action\":\"cancel\"}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
updateMsgForm(null, null, 0);
}
private void requestCreateZipFileFolder(string path, string zip, string[] files)
{
// Send ZIP command
string cmd = "{\"action\":\"zip\",\"reqid\":5,\"path\":\"" + path.Replace("\\", "/") + "\",\"output\":\"" + zip.Replace("\\", "/") + "\",\"files\":[";
bool first = true;
foreach (string file in files)
{
if (first) { first = false; } else { cmd += ","; }
cmd += "\"" + file + "\"";
}
cmd += "]}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
private void requestRename(string path, string oldname, string newname)
{
// Send RENAME command
string cmd = "{\"action\":\"rename\",\"reqid\":3,\"path\":\"" + path.Replace("\\", "/") + "\",\"oldname\":\"" + oldname + "\",\"newname\":\"" + newname + "\"}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
private void requestDelete(string path, string[] files, bool recursive)
{
// Send RM command
string delfiles = "";
foreach (string file in files) { if (delfiles.Length != 0) { delfiles += ","; } delfiles += "\"" + file + "\""; }
string cmd = "{\"action\":\"rm\",\"reqid\":4,\"path\":\"" + path.Replace("\\", "/") + "\",\"rec\":" + recursive.ToString().ToLower() + ",\"delfiles\":[" + delfiles + "]}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
private void Wc_onStringData(webSocketClient sender, string data, int orglen)
{
bytesIn += data.Length;
bytesInCompressed += orglen;
if ((state == 2) && ((data == "c") || (data == "cr")))
{
if (data == "cr") { sessionIsRecorded = true; }
state = 3;
UpdateStatus();
displayMessage(null);
// Send protocol
string cmd = "5";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
// Ask for root level
requestRemoteFolder("");
return;
}
if (state != 3) return;
// Parse the received JSON
Dictionary<string, object> jsonAction = new Dictionary<string, object>();
jsonAction = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(data);
if (jsonAction == null) return;
if (jsonAction.ContainsKey("action") && (jsonAction["action"].GetType() == typeof(string)))
{
string action = jsonAction["action"].ToString();
switch (action)
{
case "download":
{
if (downloadStop) { downloadCancel(); return; }
string sub = null;
if (jsonAction.ContainsKey("sub")) { sub = (string)jsonAction["sub"]; }
if (sub == "start")
{
// Send DOWNLOAD startack command
string cmd = "{\"action\":\"download\",\"sub\":\"startack\",\"id\":" + (downloadFileArrayPtr + 1000) + "}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
else if (sub == "cancel")
{
// Unable to download this file
if (transferStatusForm != null) { transferStatusForm.addErrorMessage(String.Format(Translate.T(Properties.Resources.ErrorDownloadingFileX), downloadFileArray[downloadFileArrayPtr].ToString())); }
// Send DOWNLOAD command
string cmd = "{\"action\":\"download\",\"sub\":\"stop\",\"id\":" + (downloadFileArrayPtr + 1000) + "}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
if (downloadFileStream != null) { downloadFileStream.Close(); downloadFileStream = null; } // Close the file
try { File.Delete(Path.Combine(downloadLocalPath.FullName, downloadFileArray[downloadFileArrayPtr].ToString())); } catch (Exception) { }
// Go to next file
if (downloadFileArray.Count > downloadFileArrayPtr + 1)
{
// Download the next file
downloadFileArrayPtr++;
downloadNextFile();
}
else
{
// Done with all files
downloadActive = false;
downloadStop = false;
downloadFileArrayPtr = -1;
downloadFileArray = null;
downloadLocalPath = null;
downloadRemotePath = null;
closeTransferDialog();
localRefresh();
}
}
break;
}
}
}
else if (jsonAction.ContainsKey("type") && (jsonAction["type"].GetType() == typeof(string))) {
string action = jsonAction["type"].ToString();
switch (action)
{
case "metadata":
{
if ((jsonAction.ContainsKey("users") == false) || (jsonAction["users"] == null)) return;
Dictionary<string, object> usersex = (Dictionary<string, object>)jsonAction["users"];
userSessions = new Dictionary<string, int>();
foreach (string user in usersex.Keys) { userSessions.Add(user, (int)usersex[user]); }
UpdateStatus();
break;
}
case "console":
{
string msg = null;
int msgid = -1;
if ((jsonAction.ContainsKey("msg")) && (jsonAction["msg"] != null)) { msg = jsonAction["msg"].ToString(); }
if (jsonAction.ContainsKey("msgid")) { msgid = (int)jsonAction["msgid"]; }
if (msgid == 1) { msg = Translate.T(Properties.Resources.WaitingForUserToGrantAccess); }
if (msgid == 2) { msg = Translate.T(Properties.Resources.Denied); }
if (msgid == 3) { msg = Translate.T(Properties.Resources.FailedToStartRemoteTerminalSession); }
if (msgid == 4) { msg = Translate.T(Properties.Resources.Timeout); }
if (msgid == 5) { msg = Translate.T(Properties.Resources.ReceivedInvalidNetworkData); }
displayMessage(msg);
break;
}
}
}
}
private void Wc_onBinaryData(webSocketClient sender, byte[] data, int offset, int length, int orglen)
{
bytesIn += length;
bytesInCompressed += orglen;
if (state != 3) return;
if (data[offset] == 123) {
// Parse the received JSON
Dictionary<string, object> jsonAction = new Dictionary<string, object>();
jsonAction = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(UTF8Encoding.UTF8.GetString(data, offset, length));
if (jsonAction == null) return;
int reqid = 0;
if (jsonAction.ContainsKey("reqid")) { reqid = (int)jsonAction["reqid"]; }
string action = null;
if (jsonAction.ContainsKey("action")) { action = (string)jsonAction["action"]; }
if (action == "uploadstart")
{
if (uploadStop) { uploadCancel(); return; }
uploadNextPart(false);
for (var i = 0; i < 8; i++) { uploadNextPart(true); }
}
else if (action == "uploadack")
{
if (uploadStop) { uploadCancel(); return; }
uploadNextPart(false);
}
else if ((action == "uploaddone") || (action == "uploaderror"))
{
// Clean up current upload
uploadFilePtr = 0;
uploadFileStartPtr = 0;
uploadFileSize = 0;
if (uploadFileStream != null) { uploadFileStream.Close(); uploadFileStream = null; }
// If this is an error, show it in the dialog
if ((action == "uploaderror") && (transferStatusForm != null)) { transferStatusForm.addErrorMessage(String.Format(Translate.T(Properties.Resources.ErrorUploadingFileX), uploadFileName)); }
// Check if another file needs to be uploaded
if (uploadFileArray.Count > (uploadFileArrayPtr + 1))
{
// Upload the next file
uploadFileArrayPtr++;
uploadNextFile();
}
else
{
// Done with all files
uploadActive = false;
uploadStop = false;
uploadFileArrayPtr = -1;
uploadFileArray = null;
uploadFileDuplicateArray = null;
uploadLocalPath = null;
uploadRemotePath = null;
uploadFilePtr = 0;
uploadFileStartPtr = 0;
uploadFileSize = 0;
uploadFileName = null;
closeTransferDialog();
remoteRefresh();
}
}
else if (action == "uploadhash")
{
if (uploadStop) { uploadCancel(); return; }
string name = null;
if (jsonAction.ContainsKey("name")) { name = (string)jsonAction["name"]; }
string path = null;
if (jsonAction.ContainsKey("path")) { path = (string)jsonAction["path"]; }
string remoteHashHex = null;
if (jsonAction.ContainsKey("hash")) { remoteHashHex = (string)jsonAction["hash"]; }
long remoteFileSize = 0;
if (jsonAction.ContainsKey("tag")) {
if (jsonAction["tag"].GetType() == typeof(int)) { remoteFileSize = (int)jsonAction["tag"]; }
if (jsonAction["tag"].GetType() == typeof(long)) { remoteFileSize = (long)jsonAction["tag"]; }
}
if ((uploadRemotePath != path) || (uploadFileName != name)) { uploadCancel(); return; }
// Hash the local file
string localHashHex = null;
try
{
string filePath = Path.Combine(localFolder.FullName, uploadFileName);
using (SHA384 SHA384 = SHA384Managed.Create())
{
uploadFileStream.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[65536];
long ptr = 0;
int len = 1;
while (len != 0)
{
int l = buf.Length;
if (l > (remoteFileSize - ptr)) { l = (int)(remoteFileSize - ptr); }
if (l == 0) { len = 0; } else { len = uploadFileStream.Read(buf, 0, l); }
if (len > 0) { SHA384.TransformBlock(buf, 0, len, buf, 0); }
ptr += len;
}
SHA384.TransformFinalBlock(buf, 0, 0);
localHashHex = BitConverter.ToString(SHA384.Hash).Replace("-", string.Empty);
uploadFileStream.Seek(0, SeekOrigin.Begin);
}
}
catch (Exception) { }
if ((localHashHex != null) && (localHashHex.Equals(remoteHashHex)))
{
if (remoteFileSize == uploadFileStream.Length)
{
// Files are the same length, skip the file.
// Check if another file needs to be uploaded
if (uploadFileArray.Count > (uploadFileArrayPtr + 1))
{
// Upload the next file
uploadFileArrayPtr++;
uploadNextFile();
}
else
{
// Done with all files
uploadActive = false;
uploadStop = false;
uploadFileArrayPtr = -1;
uploadFileArray = null;
uploadFileDuplicateArray = null;
uploadLocalPath = null;
uploadRemotePath = null;
uploadFilePtr = 0;
uploadFileStartPtr = 0;
uploadFileSize = 0;
uploadFileName = null;
closeTransferDialog();
remoteRefresh();
}
}
else
{
// Files are not the same length, append the rest
uploadFileStream.Seek(remoteFileSize, SeekOrigin.Begin);
uploadFilePtr = uploadFileStartPtr = remoteFileSize;
// Send UPLOAD command with append turned on
string cmd = "{\"action\":\"upload\",\"reqid\":" + (uploadFileArrayPtr + 1000) + ",\"path\":\"" + uploadRemotePath + "\",\"name\":\"" + name + "\",\"size\":" + uploadFileSize + ",\"append\":true}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
}
else
{
// Send UPLOAD command
string cmd = "{\"action\":\"upload\",\"reqid\":" + (uploadFileArrayPtr + 1000) + ",\"path\":\"" + uploadRemotePath + "\",\"name\":\"" + name + "\",\"size\":" + uploadFileSize + "}";
byte[] bincmd = UTF8Encoding.UTF8.GetBytes(cmd);
wc.SendBinary(bincmd, 0, bincmd.Length);
}
}
else if ((action == "dialogmessage"))
{
// Dialog box message
string msg = null;
string file = null;
int progress = 0;
if (jsonAction.ContainsKey("msg") && (jsonAction["msg"] == null)) { msg = ""; }
else if (jsonAction.ContainsKey("msg") && (jsonAction["msg"].GetType() == typeof(string))) { msg = (string)jsonAction["msg"]; }
if (jsonAction.ContainsKey("file") && (jsonAction["file"].GetType() == typeof(string))) { file = (string)jsonAction["file"]; }
if (jsonAction.ContainsKey("progress") && (jsonAction["progress"].GetType() == typeof(System.Int32))) { progress = (int)jsonAction["progress"]; }
updateMsgForm(msg, file, progress);
}
else if (reqid == 1)
{
// Result of a LS command
if (jsonAction.ContainsKey("path")) { remoteFolder = (string)jsonAction["path"]; }
if (jsonAction.ContainsKey("dir")) { remoteFolderList = (ArrayList)jsonAction["dir"]; }
updateRemoteFileView();
}
}
else
{
if (downloadActive) {
if (downloadStop) { downloadCancel(); return; }
downloadGotBinaryData(data, offset, length);
}
}
}
public delegate void updateMsgFormHandler(string msg, string file, int progress);
private void updateMsgForm(string msg, string file, int progress)
{
if (this.InvokeRequired) { this.Invoke(new updateMsgFormHandler(updateMsgForm), msg, file, progress); return; }
if ((msg == null) || (msg == ""))
{
// Close the dialog box
if (msgForm != null) { msgForm.Close(); msgForm = null; remoteRefresh(); }
}
else
{
// Open or update the dialog box
if (msgForm == null)
{
msgForm = new FileDialogMsgForm(this);
msgForm.Show(this);
msgForm.UpdateStatus(msg, file, progress);
if (msgForm.StartPosition == FormStartPosition.CenterParent)
{
var x = Location.X + (Width - msgForm.Width) / 2;
var y = Location.Y + (Height - msgForm.Height) / 2;
msgForm.Location = new Point(Math.Max(x, 0), Math.Max(y, 0));
}
}
else
{
msgForm.UpdateStatus(msg, file, progress);
}
}
}
private delegate void remoteRefreshHandler();
private void remoteRefresh()
{
if (this.InvokeRequired) { this.Invoke(new remoteRefreshHandler(remoteRefresh)); return; }
updateTimer.Enabled = true;
}
private delegate void localRefreshHandler();
private void localRefresh()
{
if (this.InvokeRequired) { this.Invoke(new localRefreshHandler(localRefresh)); return; }
updateLocalFileView();
}
private void MenuItemDisconnect_Click(object sender, EventArgs e)
{
if (wc != null)
{
// Disconnect
state = 0;
wc.Dispose();
wc = null;
UpdateStatus();
}
else
{
// Connect
MenuItemConnect_Click(null, null);
}
displayMessage(null);
}
public delegate void UpdateStatusHandler();
private void UpdateStatus()
{
if (this.IsDisposed) return;
if (this.InvokeRequired) { this.Invoke(new UpdateStatusHandler(UpdateStatus)); return; }
//if (kvmControl == null) return;
switch (state)
{
case 0: // Disconnected
mainToolStripStatusLabel.Text = Translate.T(Properties.Resources.Disconnected);
connectButton.Text = Translate.T(Properties.Resources.Connect);
remoteRefreshButton.Enabled = false;
remoteUpButton.Enabled = false;
remoteRootButton.Enabled = false;
remoteNewFolderButton.Enabled = false;
remoteDeleteButton.Enabled = false;
remoteZipButton.Enabled = false;
remoteFolder = null;
break;
case 1: // Connecting
mainToolStripStatusLabel.Text = Translate.T(Properties.Resources.Connecting);
connectButton.Text = Translate.T(Properties.Resources.Disconnect);
break;
case 2: // Setup
mainToolStripStatusLabel.Text = Translate.T(Properties.Resources.Setup);
connectButton.Text = Translate.T(Properties.Resources.Disconnect);
break;
case 3: // Connected
string label = Translate.T(Properties.Resources.Connected);
if (sessionIsRecorded) { label += Translate.T(Properties.Resources.RecordedSession); }
if ((userSessions != null) && (userSessions.Count > 1)) { label += string.Format(Translate.T(Properties.Resources.AddXUsers), userSessions.Count); }
label += ".";
mainToolStripStatusLabel.Text = label;
connectButton.Text = Translate.T(Properties.Resources.Disconnect);
break;
}
rightListView.Enabled = (state == 3);
if (state != 3) { rightListView.Items.Clear(); }
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
if (wc != null)
{
// Disconnect
state = 0;
wc.Dispose();
wc = null;
UpdateStatus();
}
node.fileViewer = null;
// Clean up any downloads
if (downloadFileStream != null) { downloadFileStream.Close(); downloadFileStream = null; }
downloadFilePtr = 0;
downloadFileSize = 0;
downloadActive = false;
downloadStop = false;
downloadFileArrayPtr = -1;
downloadFileArray = null;
downloadLocalPath = null;
downloadRemotePath = null;
// Clean up any uploads
uploadActive = false;
uploadStop = false;
uploadFileArrayPtr = -1;
uploadFileArray = null;
uploadFileDuplicateArray = null;
uploadLocalPath = null;
uploadRemotePath = null;
uploadFilePtr = 0;
uploadFileStartPtr = 0;
uploadFileSize = 0;
if (uploadFileStream != null) { uploadFileStream.Close(); uploadFileStream = null; }
// Save window location
Settings.SetRegValue("filelocation", Location.X + "," + Location.Y + "," + Size.Width + "," + Size.Height);
}
public delegate void displayMessageHandler(string msg);
public void displayMessage(string msg)
{
if (this.InvokeRequired) { this.Invoke(new displayMessageHandler(displayMessage), msg); return; }
if (msg == null)
{
consoleMessage.Visible = false;
consoleTimer.Enabled = false;
}
else
{
consoleMessage.Text = msg;
consoleMessage.Visible = true;
consoleTimer.Enabled = true;
}
}
private void consoleTimer_Tick(object sender, EventArgs e)
{
consoleMessage.Visible = false;
consoleTimer.Enabled = false;
}
private void connectButton_Click(object sender, EventArgs e)
{
if (wc != null)
{
// Disconnect
state = 0;
wc.Dispose();
wc = null;
UpdateStatus();
}
else
{
// Connect
MenuItemConnect_Click(null, null);
}
displayMessage(null);
}
private void leftListView_MouseDoubleClick(object sender, MouseEventArgs e)
{
ListViewItem item = leftListView.GetItemAt(e.X, e.Y);
if (item != null)
{
if (item.Tag.GetType() == typeof(DriveInfo)) {
DirectoryInfo old = localFolder;
localFolder = ((DriveInfo)item.Tag).RootDirectory;
if (updateLocalFileView() == false) { localFolder = old; updateLocalFileView(); }
Settings.SetRegValue("LocalPath", (localFolder == null) ? "" : localFolder.FullName);
}
else if (item.Tag.GetType() == typeof(DirectoryInfo))
{
DirectoryInfo old = localFolder;
localFolder = (DirectoryInfo)item.Tag;
if (updateLocalFileView() == false) { localFolder = old; updateLocalFileView(); }
Settings.SetRegValue("LocalPath", (localFolder == null) ? "" : localFolder.FullName);
}
}
}
private void localUpButton_Click(object sender, EventArgs e)
{
localFolder = localFolder.Parent;
Settings.SetRegValue("LocalPath", (localFolder == null)?"":localFolder.FullName);
updateLocalFileView();
}
private void rightListView_MouseDoubleClick(object sender, MouseEventArgs e)
{
ListViewItem item = rightListView.GetItemAt(e.X, e.Y);
if (item != null)
{
string r = remoteFolder;
if ((item.ImageIndex == 0) || (item.ImageIndex == 1)) {
if ((r == null) || (r == "")) {
r = item.Text;
} else {
if (remoteFolder.EndsWith("/")) { r = remoteFolder + item.Text; } else { r = remoteFolder + "/" + item.Text; }
}
requestRemoteFolder(r);
}
}
}
private void remoteUpButton_Click(object sender, EventArgs e)
{
string r = remoteFolder;
if (r.EndsWith("/")) { r = r.Substring(0, r.Length - 1); }
int i = r.LastIndexOf("/");
if (i >= 0) { r = r.Substring(0, i + 1); } else { r = ""; }
requestRemoteFolder(r);
}
private void leftRefreshButton_Click(object sender, EventArgs e)
{
updateLocalFileView();
}
private void rightRefreshButton_Click(object sender, EventArgs e)
{
requestRemoteFolder(remoteFolder);
}
private void remoteNewFolderButton_Click(object sender, EventArgs e)
{
if (remoteFolder == null) return;
FilenamePromptForm f = new FilenamePromptForm(Translate.T(Properties.Resources.CreateFolder), "");
if (f.ShowDialog(this) == DialogResult.OK)
{
string r;
if (remoteFolder.EndsWith("/")) { r = remoteFolder + f.filename; } else { r = remoteFolder + "/" + f.filename; }
requestCreateFolder(r);
remoteRefresh();
}
}
private void remoteZipButton_Click(object sender, EventArgs e)
{
if (remoteFolder == null) return;
FilenamePromptForm f = new FilenamePromptForm(Translate.T(Properties.Resources.ZipSelectedFiles), "");
if (f.ShowDialog(this) == DialogResult.OK)
{
string r = f.filename;