public void FirstStartUp() { Controls.Clear(); int tabNumber = 0; //TXT: Browse input Controls.Add(txtPath); txtPath.TabIndex = tabNumber++; //BTN: Browse menu btnBrowse.TabIndex = tabNumber++; Controls.Add(btnBrowse); //CHK: Folder option chkCreateFolder.TabIndex = tabNumber++; Controls.Add(chkCreateFolder); //BTN: Confirm path btnConfirmPath.TabIndex = tabNumber++; Controls.Add(btnConfirmPath); //Labels Controls.Add(lblBrowse); AcceptButton = btnConfirmPath; if (DiskHelper.GetRegistryValue("Path") != null) { txtPath.Text = DiskHelper.GetRegistryValue("Path"); } }
private void BtnConfirmPathClick(object sender, EventArgs e) { string hiddenPath = PathName() + @".hidden\", newPath = PathName() + @"TorPdos\"; if (Directory.Exists(PathName()) == true) { if (!Directory.Exists(hiddenPath) && chkCreateFolder.Checked == false) { DiskHelper.SetRegistryValue("Path", PathName()); HiddenFolder dih = new HiddenFolder(hiddenPath); } else if (Directory.Exists(hiddenPath) && chkCreateFolder.Checked == false) { DiskHelper.SetRegistryValue("Path", PathName()); } else if (chkCreateFolder.Checked == true) { DiskHelper.SetRegistryValue("Path", newPath); DirectoryInfo di = Directory.CreateDirectory(newPath); HiddenFolder dih = new HiddenFolder(newPath + @".hidden\"); } if (IdHandler.UserExists()) { Login(); } else { Create(); } } }
/// <summary> /// Return UUID if present, else return null. /// </summary> /// <param name="password"></param> /// <returns>UUID if present, else null.</returns> public static string GetUuid(string password) { string path = DiskHelper.GetRegistryValue("Path") + HiddenFolder + UserDataFile; if (UserExists()) { try{ if (_uuId != null) { return(_uuId); } string[] userdata = FileEncryption.UserDataDecrypt(password, path); _uuId = userdata[1]; _keyMold = userdata[0]; return(_uuId); } catch (Exception) { //return null; return("Invalid Password"); } } else { return(null); } }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); string fileName = req.Query["name"]; string blockSizeStr = req.Query["block"]; string mode = req.Query["mode"]; int blockSize; if (!int.TryParse(blockSizeStr, out blockSize)) { blockSize = 1024 * 10; } bool random = false; random = string.IsNullOrWhiteSpace(mode) ? false : (mode == "random"); Stopwatch sw = Stopwatch.StartNew(); int fileSize = random ? DiskHelper.DiskReadRandom(fileName, blockSize) : DiskHelper.DiskRead(fileName, blockSize); sw.Stop(); double time = fileSize == 0 ? 0.0 : sw.Elapsed.TotalMilliseconds; string result = $"{time:n2}"; if (time == 0.0) { result += $", {Path.Combine(Path.GetTempPath(), fileName)}"; result += $", {Environment.MachineName}"; } return((ActionResult) new OkObjectResult(result)); }
/// <summary> /// Function to receive upload message /// </summary> /// <param name="uploadMessage">The message to be received</param> private void ReceivedUpload(UploadMessage uploadMessage) { if (uploadMessage.type.Equals(TypeCode.REQUEST)) { int replyPort = uploadMessage.port; string uuid = uploadMessage.fromUuid; if (DiskHelper.GetTotalAvailableSpace(@"C:\") > uploadMessage.filesize) { uploadMessage.statusCode = StatusCode.ACCEPTED; Console.WriteLine(@"Request accepted"); } else { Console.WriteLine(@"Not enough space"); uploadMessage.statusCode = StatusCode.INSUFFICIENT_STORAGE; } uploadMessage.CreateReply(); uploadMessage.port = _ports.GetAvailablePort(); _fileReceiver = new FileReceiver(this._path + @".hidden\" + uuid + @"\" + uploadMessage.fullFilename + @"\", uploadMessage.chunkHash, uploadMessage.port); _fileReceiver.Start(); uploadMessage.Send(replyPort); } _ports.Release(uploadMessage.port); }
/// <summary> /// Create user file using generated UUID and input password. /// UUID can be sent in as input, for a custom UUID. /// </summary> /// <param name="password">The input password from user.</param> /// <param name="uuid">User UUID (if the user already has an UUID).</param> /// <returns>UUID</returns> public static string CreateUser(string password, string uuid = null) { try{ if (uuid == null) { uuid = GenerateUuid(); } else { if (uuid.Length > 32) { uuid = uuid.Substring(0, 32); } } string path = DiskHelper.GetRegistryValue("Path") + HiddenFolder + UserDataFile; _keyMold = GenerateKeyMold(uuid, password); string output = _keyMold + "\n" + uuid; FileEncryption.UserDataEncrypt(password, output, path); Console.WriteLine("NEW USER: " + uuid); return(uuid); } catch (Exception) { return(null); } }
void BtnLoginClick(object sender, EventArgs e) { string pass = txtPassword.Text; string path = DiskHelper.GetRegistryValue("Path"); if (IdHandler.IsValidUser(pass)) { IdHandler.GetUuid(pass); LoggedIn(); loggedIn = true; _idx = new Index(path); _p2P = new Network(25565, _idx, path); _p2P.Start(); _idx.Load(); IndexEventHandlers(); if (!_idx.Load()) { _idx.BuildIndex(); } _idx.Start(); _idx.MakeIntegrityCheck(); } else { Controls.Add(lblNope); } }
public IActionResult CreateFolder(CreateFolderRequest request) { if (_folderRepo.Any(f => f.FolderName == request.NewFolderName && f.ParentFolderId == request.ParentFolderId)) { return(BadRequest("В текущей папке уже существует папка с таким именем")); } if (!_folderRepo.Any(f => request.ParentFolderId == f.Id) && request.ParentFolderId != Guid.Empty) { return(BadRequest("Папки с указанным id не существует!")); } if (request.ParentFolderId != Guid.Empty && !UserHasRole(request.ParentFolderId, AccessLevel.Create)) { return(BadRequest("Не достаточно уровня прав доступа!")); } var newFolder = new Folder { ParentFolderId = request.ParentFolderId, FolderName = request.NewFolderName }; DiskHelper.CreateFolder(_folderService.GetFullPath(request.ParentFolderId), request.NewFolderName); _db.Set <UsersFolders>().Add(new UsersFolders { AccessLevel = AccessLevel.Owner, User = UserContext, Folder = newFolder }); _db.Set <Folder>().Add(newFolder); _db.SaveChanges(); return(CreatedAtAction(nameof(GetFolder), routeValues: new { folderId = newFolder.Id }, newFolder.Id)); }
private void FrmMain_Load(object sender, EventArgs e) { cbDrives.Items.AddRange(DiskHelper.GetAllDiskName()); cbOstype.Items.AddRange(OsTypes); tbIP.Text = IPHelper.GetAddressIPFromKeys(configs.Select(c => c.ip).ToList()); InitDefault(); }
public IActionResult CreateFile([FromForm] InsertFileRequest request) { if (request.File == null) { return(BadRequest("Отсутствует файл в запросе")); } var folder = _folderRepo.FirstOrDefault(f => f.Id == request.FolderId); if (folder == null) { return(BadRequest("Указанная папка не существует")); } if (_fileRepo.Any(f => f.FileName == request.File.FileName && f.Folder.Id == request.FolderId)) { return(BadRequest("В данной папке уже существует файл с таким именем")); } var newFile = new File { FileName = request.File.FileName, Folder = folder, FilePath = DiskHelper.SaveToPC(request.File, _folderService.GetFullPath(request.FolderId)) }; _fileRepo.Add(newFile); _db.SaveChanges(); return(CreatedAtAction(nameof(GetFile), routeValues: new { fileId = newFile.Id }, newFile.Id)); }
protected override void OnLoad(EventArgs e) { Hide(); BelongModule.NoteDir = BelongModule.BaseDir + "\\Notes\\"; if (!Directory.Exists(BelongModule.NoteDir)) { Directory.CreateDirectory(BelongModule.NoteDir); } else { DiskHelper.EnumDirectory(BelongModule.NoteDir, delegate(string fullName, DiskHelper.DirectoryItemType type) { FileInfo info = new FileInfo(fullName); string ext = info.Extension; if (!string.IsNullOrEmpty(ext)) { ext = ext.ToLower(); if (ext.Equals(".txt")) { StickyForm sf = BelongModule.RegistNewWindow(); sf.Controller = this; sf.FileName = fullName; } } return(true); }); } base.OnLoad(e); }
/// <summary> /// Handles the deletion of a chunk of the file /// </summary> /// <param name="currentFileChunk">The P2PChunk to be deleted</param> /// <param name="currentFile">The P2PFile to wich the chunk belongs</param> /// <returns></returns> public bool ChunkDeleter(P2PChunk currentFileChunk, P2PFile currentFile){ Listener listener = new Listener(this._port); int lastIndex = currentFileChunk.peers.Count - 1; //Sends a delete message to every peer with the chunk for (int i = lastIndex; i >= 0; i--) { if (_peers.TryGetValue(currentFileChunk.peers[i], out Peer currentReceiver)) { if (!currentReceiver.IsOnline()){ return false; } var deletionMessage = new FileDeletionMessage(currentReceiver) { type = TypeCode.REQUEST, statusCode = StatusCode.OK, port = _port, fileHash = currentFileChunk.hash, fullFileHash = currentFile.hash }; //Sends the message and waits for a response, //which will then overwrite the original sent message if (listener.SendAndAwaitResponse(ref deletionMessage, 2000)) { if (deletionMessage.type.Equals(TypeCode.RESPONSE)) { currentFileChunk.RemovePeer(deletionMessage.fromUuid); if (currentFileChunk.peers.Count == 0) { currentFile.RemoveChunk(currentFileChunk.hash); } if (deletionMessage.statusCode.Equals(StatusCode.FILE_NOT_FOUND)) { DiskHelper.ConsoleWrite("File not found at peer"); } } } } } return true; }
public IActionResult UpdateFile([FromForm] UpdateFileRequest request) { if (request.UpdatedFile == null) { return(BadRequest("Отсутствует файл в запросе")); } var folder = _folderRepo.FirstOrDefault(f => f.Id == request.FolderId); if (folder == null) { return(BadRequest("Указанная папка не существует")); } if (!_fileRepo.Any(f => f.FileName == request.UpdatedFile.FileName && f.Folder.Id == request.FolderId)) { return(BadRequest("В данной папке не существует файл с таким именем")); } var file = _fileRepo.FirstOrDefault(x => x.Id == request.FileId); if (file == null) { return(BadRequest("Не найден файл для обновления")); } file.FilePath = DiskHelper.ReplaceFile(request.UpdatedFile, file.FileName, _folderService.GetFullPath(request.FolderId)); file.FileName = request.UpdatedFile.FileName; _fileRepo.Update(file); _db.SaveChanges(); return(NoContent()); }
public void BuildDiskInfo() { DiskHelper diskInfoHelper = new DiskHelper(); _serverInfo.AvailableDiskStorage = diskInfoHelper.Free; _serverInfo.UsedDiskStorage = diskInfoHelper.Used; }
/// <summary> /// Function to receive a deletion request of files on the receiver's computer /// </summary> /// <param name="message">The message with the chunks which has to be deleted</param> private void ReceivedDeletionRequest(FileDeletionMessage message) { DiskHelper.ConsoleWrite("Deletion Message Received."); if (!message.type.Equals(TypeCode.REQUEST)) { return; } if (!message.statusCode.Equals(StatusCode.OK)) { return; } string path = _path + @".hidden\" + message.fromUuid + @"\" + message.fullFileHash + @"\" + message.fileHash; DiskHelper.ConsoleWrite(path); if (File.Exists(path)) { File.Delete(path); message.statusCode = StatusCode.ACCEPTED; message.CreateReply(); message.Send(message.port); } else { message.statusCode = StatusCode.FILE_NOT_FOUND; message.CreateReply(); message.Send(message.port); } }
/// <summary> /// Function to receive download message /// </summary> /// <param name="downloadMessage">The message which has to be received</param> private void ReceivedDownloadMessage(DownloadMessage downloadMessage) { if (downloadMessage.type.Equals(TypeCode.REQUEST)) { string path = _path + @".hidden\" + downloadMessage.fromUuid + @"\" + downloadMessage.fullFileName + @"\" + downloadMessage.filehash; if (downloadMessage.statusCode == StatusCode.OK) { if (File.Exists(path)) { downloadMessage.CreateReply(); downloadMessage.statusCode = StatusCode.ACCEPTED; downloadMessage.Send(downloadMessage.port); Console.WriteLine("Response send"); } else { Console.WriteLine("File not found"); downloadMessage.CreateReply(); downloadMessage.statusCode = StatusCode.FILE_NOT_FOUND; downloadMessage.Send(downloadMessage.port); } } else if (downloadMessage.statusCode.Equals(StatusCode.ACCEPTED)) { var sender = new ChunkSender(downloadMessage.fromIp, downloadMessage.port); sender.Send(path); DiskHelper.ConsoleWrite("File send " + downloadMessage.filehash); } } }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); string fileName = req.Query["name"]; string blockSizeStr = req.Query["block"]; int blockSize; if (!int.TryParse(blockSizeStr, out blockSize)) { blockSize = 1024 * 10; } Stopwatch sw = Stopwatch.StartNew(); int fileSize = await DiskHelper.DiskReadAsync(fileName, blockSize).ConfigureAwait(false); sw.Stop(); double time = fileSize == 0 ? 0.0 : sw.Elapsed.TotalMilliseconds; string result = $"{time:n2}"; if (time == 0.0) { result += $", {Path.Combine(Path.GetTempPath(), fileName)}"; result += $", {Environment.MachineName}"; } return(fileName != null ? (ActionResult) new OkObjectResult($"{result}") : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
public MyForm() { EventHandlers(); GuiLayout(); if (!string.IsNullOrEmpty(IdHandler.GetUuid())) { LoggedIn(); } else { if (NetworkPorts.IsPortAvailable(25565) == false) { Sorry(); } else if (String.IsNullOrEmpty(DiskHelper.GetRegistryValue("Path")) == true || Directory.Exists(DiskHelper.GetRegistryValue("Path")) == false) { FirstStartUp(); } else if (File.Exists(DiskHelper.GetRegistryValue("Path") + @".hidden\userdata") == false) { Create(); } else { Login(); } } }
public FileDownloader(NetworkPorts ports, ConcurrentDictionary <string, Peer> peers, int bufferSize = 1024) { _ports = ports; this._ip = IPAddress.Any; this._path = DiskHelper.GetRegistryValue("Path") + @".hidden\incoming\"; this._buffer = new byte[bufferSize]; this._peers = peers; }
/// <summary> /// Function to receive peers from one or your peers peer list /// </summary> /// <param name="message">It is the message which is sent to the receiver</param> private void ReceivedPeerFetch(PeerFetcherMessage message) { if (message.type.Equals(TypeCode.REQUEST)) { var outgoing = new List <Peer>(); var incoming = message.peers; // Adding sender to list if (!InPeerList(message.fromUuid, _peers)) { _peers.TryAdd(message.fromUuid, new Peer(message.fromUuid, message.fromIp)); } //Checks whether a incomming peer exists in the peerlist. foreach (var incomingPeer in incoming) { if (InPeerList(incomingPeer.GetUuid(), _peers)) { break; } _peers.TryAdd(incomingPeer.GetUuid(), incomingPeer); DiskHelper.ConsoleWrite("Peer added: " + incomingPeer.GetUuid()); } foreach (var outGoingPeer in _peers) { if (InPeerList(outGoingPeer.Value.GetUuid(), incoming)) { break; } if (outGoingPeer.Value.GetUuid() == message.fromUuid) { break; } outgoing.Add(outGoingPeer.Value); } message.CreateReply(); message.peers = outgoing; message.Send(); } else { // Rechieved response foreach (Peer incomingPeer in message.peers) { if (InPeerList(incomingPeer.GetUuid(), _peers)) { break; } if ((IdHandler.GetUuid().Equals(incomingPeer.GetUuid()))) { break; } _peers.TryAdd(incomingPeer.GetUuid(), incomingPeer); Console.WriteLine("Peer added: " + incomingPeer.GetUuid()); } } }
/// <summary> /// This is a helper function for the fetching function, this is responsible for downloading the chunk. /// </summary> /// <param name="fullFileName">Full name of the file.</param> /// <param name="port">Port for which to download from.</param> private bool Downloader(string fullFileName, int port) { int timeout = 3000; int timeoutCounter = 0; var server = new TcpListener(this._ip, port); try{ server.AllowNatTraversal(true); server.Server.ReceiveTimeout = 1000; server.Server.SendTimeout = 1000; server.Start(); }catch (Exception e) { Logger.Error(e); return(false); } while (!server.Pending()) { if (timeoutCounter >= timeout) { server.Stop(); return(false); } timeoutCounter++; Thread.Sleep(5); } try { var client = server.AcceptTcpClient(); client.ReceiveTimeout = 1000; client.Client.ReceiveTimeout = 1000; using (NetworkStream stream = client.GetStream()){ using (var fileStream = File.Open(_path + fullFileName + @"\" + _hash, FileMode.OpenOrCreate, FileAccess.Write)){ DiskHelper.ConsoleWrite("Creating file: " + this._hash); int i; while ((i = stream.Read(_buffer, 0, _buffer.Length)) > 0) { fileStream.Write(_buffer, 0, (i < _buffer.Length) ? i : _buffer.Length); } fileStream.Close(); } stream.Close(); _ports.Release(port); return(true); } } catch (Exception e) { DiskHelper.ConsoleWrite("The peer requested went offline in Downloader." + e); return(false); } }
private void RestoreOriginalFile(string path, P2PFile fileInformation) { DiskHelper.ConsoleWrite("File exist"); string pathWithoutExtension = (_path + @".hidden\incoming\" + fileInformation.hash); //Merge files var splitterLibrary = new SplitterLibrary(); if (!splitterLibrary.MergeFiles(_path + @".hidden\incoming\" + fileInformation.hash + @"\", pathWithoutExtension + ".aes", fileInformation.GetChunksAsString())) { _queue.Enqueue(fileInformation); return; } // Decrypt file var decryption = new FileEncryption(pathWithoutExtension, ".lzma"); if (!decryption.DoDecrypt(IdHandler.GetKeyMold())) { _queue.Enqueue(fileInformation); return; } DiskHelper.ConsoleWrite("File decrypted"); File.Delete(path); // Decompress file string pathToFileForCopying = Compressor.DecompressFile(pathWithoutExtension + ".lzma", pathWithoutExtension); DiskHelper.ConsoleWrite("File decompressed"); foreach (string filePath in _index.GetEntry(_fileHash).paths) { if (!Directory.Exists(Path.GetDirectoryName(filePath))) { Directory.CreateDirectory(Path.GetDirectoryName(filePath) ?? throw new NullReferenceException()); } try{ if (!File.Exists(filePath)) { File.Copy(pathToFileForCopying, filePath); DiskHelper.ConsoleWrite($"File saved to: {filePath}"); } } catch (Exception e) { logger.Error(e); } } }
/// <summary> /// Removes userdata file. /// </summary> /// <returns>Rather the removal was successful or not.</returns> public static bool RemoveUser() { try{ string path = DiskHelper.GetRegistryValue("Path") + HiddenFolder + UserDataFile; File.Delete(path); return(true); } catch (Exception) { return(false); } }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); string fileName = req.Query["name"]; string result = DiskHelper.Delete(fileName); return(fileName != null ? (ActionResult) new OkObjectResult($"0.0, File delete: ({result})") : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
/// <summary> /// Check if UUID and password match existing local user. /// Compare keymolds (hashes). /// </summary> /// <param name="password">The password input of the user.</param> /// <returns>Returns true if user details are valid, false if not.</returns> public static bool IsValidUser(string password) { try{ string path = DiskHelper.GetRegistryValue("Path") + HiddenFolder + UserDataFile; FileEncryption.UserDataDecrypt(password, path); return(true); } catch (Exception) { return(false); } }
/// <summary> /// Generate UUID based on mac addresses and current time. /// </summary> /// <returns>UUID.</returns> private static string GenerateUuid() { string guid = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(); List <string> macAddresses = NetworkHelper.GetMacAddresses(); foreach (string mac in macAddresses) { guid += mac; } return(DiskHelper.CreateMd5(guid)); }
/// <summary> /// Checks rather the user exists. /// </summary> /// <returns>Rather the user exists or not.</returns> public static bool UserExists() { string path = DiskHelper.GetRegistryValue("Path") + HiddenFolder + UserDataFile; if (File.Exists(path)) { return(true); } else { return(false); } }
public UploadManager(StateSaveConcurrentQueue <P2PFile> queue, NetworkPorts ports, ConcurrentDictionary <string, Peer> peers) { this._queue = queue; this._ports = ports; this._peers = peers; this._waitHandle = new ManualResetEvent(false); this._queue.ElementAddedToQueue += QueueElementAddedToQueue; _hiddenFolder = new HiddenFolder(_path + @".hidden"); this._path = DiskHelper.GetRegistryValue("Path"); Peer.PeerSwitchedOnline += PeerWentOnline; }
public DownloadManager(StateSaveConcurrentQueue <P2PFile> queue, NetworkPorts ports, ConcurrentDictionary <string, Peer> peers, Index index) { this._queue = queue; this._ports = ports; this._peers = peers; this._path = DiskHelper.GetRegistryValue("Path"); this._waitHandle = new ManualResetEvent(false); this._index = index; this._queue.ElementAddedToQueue += QueueElementAddedToQueue; _ports.GetAvailablePort(); this._fileDownloader = new FileDownloader(ports, _peers); Peer.PeerSwitchedOnline += PeerWentOnlineCheck; }
/// <summary> /// Pushes the inputted chunk to the network, sending it the required amount of peers. /// </summary> /// <param name="chunk">The chunk to push to the network</param> /// <param name="chunkPath">String path to the chunks</param> /// <param name="numberOfRecevingPeers">The number of peers to send the file to, /// this will be the amount of receivers, unless the network is smaller than the given input.</param> /// <param name="receiverOffset">The offset for whom to send the files to, this determines the spacing of the chunks on the peerlist.</param> /// <returns>Boolean of whether the push was a success.</returns> public bool Push(P2PChunk chunk, string chunkPath, int numberOfRecevingPeers = 10, int receiverOffset = 0) { this._port = _ports.GetAvailablePort(); List <Peer> peers = this.GetPeers(); FileInfo fileInfo = new FileInfo(chunkPath); Listener listener = new Listener(this._port); bool sendToAll = true; int listLength = peers.Count; int peerCount; int numberOfReceivers = Math.Min(numberOfRecevingPeers, listLength); for (peerCount = 0; peerCount < numberOfReceivers; peerCount++) { Peer currentPeer = peers[(peerCount + receiverOffset) % listLength]; var upload = new UploadMessage(currentPeer) { filesize = fileInfo.Length, fullFilename = chunk.originalHash, chunkHash = chunk.hash, path = chunkPath, port = this._port }; if (listener.SendAndAwaitResponse(ref upload, 2000)) { if (upload.statusCode == StatusCode.ACCEPTED) { ChunkSender sender = new ChunkSender(currentPeer.StringIp, upload.port); if (sender.Send(chunkPath)) { DiskHelper.ConsoleWrite($"The chunk {chunk.hash} was sent to {currentPeer.GetUuid()}"); chunk.AddPeer(currentPeer.GetUuid()); } else { sendToAll = false; } _ports.Release(upload.port); } } } _ports.Release(this._port); return(sendToAll); }