/// <summary> /// To send GZip file through tcp client /// </summary> /// <param name="objTrasportData">Data to be send</param> public void SendGZipFile(TrasportData objTrasportData) { Socket socket = tcpClient.Client; socket.Send(objTrasportData.GetHeaderBytes()); //Send data if (objTrasportData.FilePath == string.Empty) { socket.Send(objTrasportData.DataStream.ToArray()); } //Read GZipFile content else { byte[] buffer = new byte[8192]; int readCount = 0; int sum = 0; //Read GZipFile content using (Stream file = new GZipStream(new FileStream(objTrasportData.FilePath, FileMode.Open, FileAccess.Read), CompressionMode.Compress)) { while ((readCount = file.Read(buffer, 0, buffer.Length)) > 0) { socket.Send(buffer, 0, readCount, SocketFlags.None); sum += readCount; } } } }
/// <summary> /// Write data to tcp client stream and notify totalByte, totalByteUploaded,success information. /// </summary> /// <param name="objTrasportData">Data to be send</param> /// <param name="totalByte">Total byte to be send</param> /// <param name="totalByteUploaded">Total byte sent</param> /// <param name="success">Whether data uploaded successfully.</param> public void Send(TrasportData objTrasportData, ref long totalByte, ref long totalByteUploaded, ref bool success) { Socket socket = tcpClient.Client; socket.Send(objTrasportData.GetHeaderBytes()); //Send data if (objTrasportData.FilePath == string.Empty) { totalByte = objTrasportData.DataStream.Length; totalByteUploaded = socket.Send(objTrasportData.DataStream.ToArray()); } //Send file data else { byte[] buffer = new byte[8192]; int readCount = 0; //Read file content using (FileStream file = new FileStream(objTrasportData.FilePath, FileMode.Open, FileAccess.Read)) { totalByte = file.Length; while ((readCount = file.Read(buffer, 0, buffer.Length)) > 0) { //If user break if (success == false) { break; } totalByteUploaded += socket.Send(buffer, 0, readCount, SocketFlags.None); } } } }
/// <summary> /// Read data from tcp client stream and notify totalByte, totalByteRecceived, success information. /// </summary> /// <param name="filePath">File path where to store data.</param> /// <param name="totalByte">Total byte to be received.</param> /// <param name="totalByteRecceived">Total byte received.</param> /// <param name="success">Whether data received successfully.</param> /// <returns></returns> public TrasportData Receive(string filePath, ref long totalByte, ref long totalByteRecceived, ref bool success) { Stream stream = tcpClient.GetStream(); TrasportData objTrasportData = new TrasportData(); StringBuilder header = new StringBuilder(); StringBuilder response = new StringBuilder(); int readCount = 0; int contentLength = 0; header.Append(ReadHeader(stream)); objTrasportData.Operation = new Regex("(.*): ([0-9]*)").Match(header.ToString()).Groups[1].Value; //Read header info. foreach (Match match in (new Regex("(.*)= (.*)\r\n").Matches(header.ToString()))) { objTrasportData.Header.Add(match.Groups[1].Value, match.Groups[2].Value); } contentLength = Convert.ToInt32(new Regex("(.*): ([0-9]*)").Match(header.ToString()).Groups[2].Value); totalByte = contentLength; byte[] bytes = new byte[ReadBufferSize]; //Create file to store received data. using (FileStream file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { while (contentLength > 0) { //If user stopped receiving data. if (success == false) { break; } readCount = 0; //Read data bucket by bucket(bucket size is ReadBufferSize) if (contentLength >= ReadBufferSize) { readCount = stream.Read(bytes, 0, ReadBufferSize); totalByteRecceived += readCount; file.Write(bytes, 0, readCount); contentLength = contentLength - readCount; } //Read last bucket data else { readCount = stream.Read(bytes, 0, contentLength); totalByteRecceived += readCount; file.Write(bytes, 0, readCount); contentLength = contentLength - readCount; } } } objTrasportData.FilePath = filePath; return(objTrasportData); }
/// <summary> /// Read data from tcp client stream. /// </summary> /// <returns>Received data and formatted as per protocol</returns> public TrasportData Receive() { Stream stream = tcpClient.GetStream(); TrasportData objTrasportData = new TrasportData(); StringBuilder header = new StringBuilder(); StringBuilder response = new StringBuilder(); int readCount = 0; int contentLength = 0; header.Append(ReadHeader(stream)); objTrasportData.Operation = new Regex("(.*): ([0-9]*)").Match(header.ToString()).Groups[1].Value; //Read header info. foreach (Match match in (new Regex("(.*)= (.*)\r\n").Matches(header.ToString()))) { objTrasportData.Header.Add(match.Groups[1].Value, match.Groups[2].Value); } //Read body content length. contentLength = Convert.ToInt32(new Regex("(.*): ([0-9]*)").Match(header.ToString()).Groups[2].Value); byte[] bytes = new byte[contentLength]; //Read request body while (readCount < contentLength) { readCount += stream.Read(bytes, readCount, contentLength - readCount); } objTrasportData.DataStream.Write(bytes, 0, contentLength); //Seek memory stream to begin if (objTrasportData.DataStream.Length > 0) { objTrasportData.DataStream.Seek(0, SeekOrigin.Begin); } return(objTrasportData); }
/// <summary> /// Here port is listening to receive command from appedo and execute VBS from appedo. /// </summary> private void SLASlaveListener() { try { while ((true)) { ExceptionHandler.WritetoEventLog("TcpListener listen on " + _port.ToString()); Trasport controller = new Trasport(_serverSocket.AcceptTcpClient()); ExceptionHandler.WritetoEventLog("Request received"); new Thread(() => { try { TrasportData data = controller.Receive(); switch (data.Operation.ToLower()) { case "test": { controller.Send(new TrasportData("ok", string.Empty, null)); } break; // Executes VBS case "action": { ExceptionHandler.WritetoEventLog("action request received"); string filePath = System.IO.Path.GetTempPath() + "\\" + DateTime.Now.Ticks.ToString() + ".vbs"; string secIP = data.Header["secondaryip"]; string secPort = data.Header["secondaryport"]; data.Save(filePath); ExceptionHandler.WritetoEventLog("File saved on " + filePath); StringBuilder result = new StringBuilder(); try { //secondaryip is na(not applicable) if (secIP.ToLower() == "na") { try { StringBuilder output = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); DateTime startTime = new DateTime(); DateTime endTime = new DateTime(); bool IsSuccess = true; ExecuteScript(filePath, ref startTime, ref endTime, ref output, ref errorOutput, ref IsSuccess); Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("os", constants.OSName); headers.Add("actionstarttime", Utility.GetInstance().GetEpochTime(startTime)); headers.Add("startoffset", DateTimeOffset.Now.Offset.TotalMinutes.ToString()); headers.Add("actionendtime", Utility.GetInstance().GetEpochTime(endTime)); headers.Add("endoffset", DateTimeOffset.Now.Offset.TotalMinutes.ToString()); headers.Add("error", ""); headers.Add("log", DateTime.Now.Ticks.ToString() + ".log"); //Script executed successfully. if (IsSuccess == true) { controller.Send(new TrasportData("OK", output.ToString(), headers)); } //Unable to execute script. else { headers["error"] = "Unable to execute given script"; controller.Send(new TrasportData("ERROR", errorOutput.ToString(), headers)); } //Delete script file after execution if script file exists. if (File.Exists(filePath)) { File.Delete(filePath); } } catch (Exception ex) { ExceptionHandler.WritetoEventLog(ex.StackTrace + ex.Message); } } //Response contains secondaryip. else { try { Trasport chiled = new Trasport(secIP, secPort); Dictionary <string, string> header = new Dictionary <string, string>(); header.Add("secondaryip", "na"); header.Add("secondaryport", "na"); chiled.Send(new TrasportData("action", header, filePath)); TrasportData chiledResult = chiled.Receive(); controller.Send(chiledResult); if (File.Exists(filePath)) { File.Delete(filePath); } } catch (Exception ex) { Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("os", constants.OSName); headers.Add("actionstarttime", Utility.GetInstance().GetEpochTime(DateTime.Now)); headers.Add("startoffset", DateTimeOffset.Now.Offset.TotalMinutes.ToString()); headers.Add("actionendtime", Utility.GetInstance().GetEpochTime(DateTime.Now)); headers.Add("endoffset", DateTimeOffset.Now.Offset.TotalMinutes.ToString()); headers.Add("error", ex.Message.ToString()); headers.Add("log", "sample.log"); controller.Send(new TrasportData("ERROR", ex.Message.ToString(), headers)); } } } catch (Exception ex) { ExceptionHandler.WritetoEventLog(ex.StackTrace + ex.Message); } } break; } controller.Close(); } catch (Exception ex) { ExceptionHandler.WritetoEventLog(ex.StackTrace + ex.Message); } }).Start(); } } catch (Exception ex) { ExceptionHandler.WritetoEventLog(ex.StackTrace + ex.Message); } }