We are developing a winforms client with C#, for sending SSH commands using plink.exe. We have got the following method. But we execute it, standard error gives "FATAL ERROR : Server unexpectedly closed network connection".
The same command (plink.exe + arguments) is executed successfully in the command line.
Any idea?
Thanks.
public string SendSSHCommand(string host, string userName, string password, string commandFile, string logPath, int maxRetryCount)
{
string result = String.Empty;
string commandText = "plink.exe";
Process sshProcess = new Process();
sshProcess.StartInfo = new ProcessStartInfo(commandText);
sshProcess.StartInfo.Arguments = String.Format("{0} -P 22 -ssh -l {1} -pw {2} <\"{3}\"> \"{4}\"", host, userName, password, commandFile, logPath);
sshProcess.StartInfo.WorkingDirectory = Parameters.RootDirectory;
sshProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
sshProcess.StartInfo.CreateNoWindow = true;
sshProcess.StartInfo.UseShellExecute = false;
sshProcess.StartInfo.RedirectStandardInput = true;
sshProcess.StartInfo.RedirectStandardError = true;
sshProcess.StartInfo.RedirectStandardOutput = true;
//sshProcess.EnableRaisingEvents = true;
_logger.Log("SSH Command : " + commandText + " " + sshProcess.StartInfo.Arguments);
int iteration = 0;
while (iteration <= maxRetryCount)
{
iteration++;
sshProcess.Start();
//Thread.Sleep(2000); // wait for two seconds.
sshProcess.StandardInput.WriteLine("y");
sshProcess.WaitForExit();
string output = sshProcess.StandardOutput.ReadToEnd();
string error = sshProcess.StandardError.ReadToEnd();
_logger.Log("STANDARD OUTPUT : " + output);
_logger.Log("STANDARD ERROR : " + error);
if (File.Exists(logPath))
{
using (StreamReader sr = new StreamReader(logPath))
{
result = sr.ReadToEnd();
}
File.Delete(logPath);
}
else
{
result = "NO RESULT FILE";
}
if (String.IsNullOrEmpty(result)) // retry needed.
{
_logger.Log("SSH command failed. Retrying after 5 seconds...");
Thread.Sleep(5000);
}
else
{
break; // command executed. no retry needed.
}
}
if (iteration >= maxRetryCount)
{
_logger.Log("Max retry count is reached.");
throw new Exception("SSH command failed after " + maxRetryCount.ToString() + " attempts.\nFailed command :\n" + commandText + " " + sshProcess.StartInfo.Arguments);
}
return result;
}
Related
I need to develop an application that is able to put out some commands after connecting to an ip with Telnet, and then just logs the ongoing responds;
So I have tried package like PrimS.Telnet and Minimalistic.Telnet; The thing is it works with other telnet servers, but not with this one; All I get are echo's in uppercases:
While when I use Putty (which I can't automate) it does give the right respond:
I have to press one enter first before getting that weird glitch character away
Is this something normal? Am I missing something here why I can't use my C# application with this server?
edit 1: I already found out that my C# does not support some telnet commands that would ask not to echo text back (see Telnet Commands). So my question is how to I parse those telnet commands so I can send them?
Ok small example for you. Method AskReceive sends a command and waits 200 mileseconds for the answer. It uses Stream to send and receive. If you send clearTextWriter.WriteLine(commandline) you are sending a string command to your device.
using System;
using System.IO;
using System.Net.Sockets;
namespace CommonCore.Classes.Helper
{
class TelnetDevice01
{
static int connectionTimeout = 1300;
string AskReceive(string commandline, ref string _log)
{
_log += "> " + commandline + Environment.NewLine;
clearTextWriter.WriteLine(commandline);
string _str;
System.Threading.Thread.Sleep(200);
_str = clearTextReader.ReadLine();
_log += "< " + _str + Environment.NewLine;
return _str;
}
void ExitError(string str, ref string _log, ref string _error)
{
_error = str;
_log += "!! Error : " + str + Environment.NewLine + Environment.NewLine;
clearTextWriter.WriteLine("QUIT");
}
StreamReader clearTextReader = null;
StreamWriter clearTextWriter = null;
public void ConnectTelnet(string login, string password, string server, int port,
out string log, out string resume, out string error
)
{
string _response = "";
resume = "";
error = "";
log = "";
TcpClient client = new TcpClient();
//Make the connection with timeout
if (!client.ConnectAsync(server, port).Wait(connectionTimeout))
{
//log = ex.ExceptionToString();
error = $"Could not connect '{server}' at port '{port}'";
log += Environment.NewLine + error + Environment.NewLine;
resume = Environment.NewLine + $"[FAIL] Port={port}. Could not connect '{server}' at port '{port}'" + Environment.NewLine;
return;
}
using (client)
{
using (NetworkStream stream = client.GetStream())
using (clearTextReader = new StreamReader(stream))
using (clearTextWriter = new StreamWriter(stream) { AutoFlush = true })
{
log += Environment.NewLine + Environment.NewLine + "## Connected" + Environment.NewLine;
//Read the start response line like "User:" ?'
string connectResponse = clearTextReader.ReadLine();
log += "< " + connectResponse + Environment.NewLine;
if (!connectResponse.StartsWith("login"))
{
ExitError(_response, ref log, ref error);
resume = Environment.NewLine + $"Expecting 'login'";
return;
}
//Send login
if (!(_response = AskReceive(login, ref log)).StartsWith("password"))
{
ExitError(_response, ref log, ref error);
resume = Environment.NewLine + $"Asnswer should have been 'password'";
return;
}
// Is asking for password, let's send the pass now
if (!(_response = AskReceive(password, ref log)).StartsWith("Login OK"))
{
ExitError(_response, ref log, ref error);
resume = Environment.NewLine + $"Answer should have been 'Login OK'";
return;
}
//Send CMD SMDR
_response = AskReceive($"SMDR", ref log);
//Check if the answer is what you want
// like _response.Contains("blabla")
}
}
}
}
}
I've just created and installed my first Windows Service. When I start the service is never changes it's status to "Started". The status stays "Starting" but the service is doing it's job. I thought that perhaps the way I'm interacting with the OnStart method. I simply get the OnStart method to call another method that executes fine. Here is a sample:
protected override void OnStart(string[] args)
{
try {
Logger("Start");
}
catch (Exception ex)
{
string filePath2 = #"C:/ProgramData/Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
}
}
What would I need to change to get the client to register that the service has started and is running. PS, the service is doing what it's meant to do.
Thanks in advance for any and all help!
EDIT
This is what Logger does:
public void Logger(string state)
{
try
{
{
Random a = new Random(Environment.TickCount);
//unique name PhoneSystem.ApplicationName = "TestApi";//any name
PhoneSystem.ApplicationName = PhoneSystem.ApplicationName + a.Next().ToString();
}
#region phone system initialization(init db server)
String filePath = #"C:/ProgramData/3CXLogger/3CXPhoneSystem.ini";
if (!File.Exists(filePath))
{
//this code expects 3CXPhoneSystem.ini in current directory.
//it can be taken from the installation folder (find it in Program Files/3CXPhone System/instance1/bin for in premiss installation)
//or this application can be run with current directory set to location of 3CXPhoneSystem.ini
//v14 (cloud and in premiss) installation has changed folder structure.
//3CXPhoneSystem.ini which contains connectio information is located in
//<Program Files>/3CX Phone System/instanceN/Bin folder.
//in premiss instance files are located in <Program Files>/3CX Phone System/instance1/Bin
throw new Exception("Cannot find 3CXPhoneSystem.ini");
}
String value = _3cxLogger.Utilities.GetKeyValue("ConfService", "ConfPort", filePath);
Int32 port = 0;
if (!String.IsNullOrEmpty(value))
{
Int32.TryParse(value.Trim(), out port);
PhoneSystem.CfgServerPort = port;
}
value = _3cxLogger.Utilities.GetKeyValue("ConfService", "confUser", filePath);
if (!String.IsNullOrEmpty(value))
PhoneSystem.CfgServerUser = value;
value = _3cxLogger.Utilities.GetKeyValue("ConfService", "confPass", filePath);
if (!String.IsNullOrEmpty(value))
PhoneSystem.CfgServerPassword = value;
#endregion
DN[] ps = PhoneSystem.Root.GetDN(); //Access PhoneSystem.Root to initialize ObjectModel
//_3cxLogger.SampleStarter.StartSample(args);
}
catch (Exception ex)
{
string filePath2 = #"C:\ProgramData\3CXLogger\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
//Console.WriteLine(ex.ToString());
}
string constring = "Data Source = LEWCOMP1\\COMPLIANCE; Initial Catalog = 3CXCallStats; Integrated Security = True";
while (state == "Start")
{
Thread.Sleep(5000);
int count = 0;
foreach (DN dn in PhoneSystem.Root.GetDN())
{
ActiveConnection[] a = dn.GetActiveConnections();
foreach (ActiveConnection ac in a)
{
try
{
if (ac.Status == ConnectionStatus.Connected)
{
count = count + 1;
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source);
string filePath2 = #"C:\ProgramData\3CXLogger\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
}
}
}
count = count / 2;
string update = "UPDATE callsCounter SET Counter = '" + count + "' WHERE ID='1';";
string insert = "INSERT Interval_Counter (Date_Time, Count) VALUES ('" + DateTime.Now + "','" + count + "')";
SqlConnection myCon = new SqlConnection(constring);
SqlCommand updateCMD = new SqlCommand(update, myCon);
SqlCommand insertCMD = new SqlCommand(insert, myCon);
SqlDataReader myReaderUpdate;
SqlDataReader myReaderInsert;
myCon.Open();
myReaderUpdate = updateCMD.ExecuteReader();
myReaderUpdate.Read();
myCon.Close();
myCon.Open();
myReaderInsert = insertCMD.ExecuteReader();
myReaderInsert.Read();
myCon.Close();
}
}
Additionaly, I checked the event logs and there are events for the service has successfully started. Odd.
Thanks for all the help!
I created a new class and started a new thread that targeted the method.
protected override void OnStart(string[] args)
{
Log oLog = new Log();
Thread t = new Thread(new ThreadStart(oLog.Logger));
t.Start();
}
The following method calls Ping.Send(). When I pass an invalid URL, Send() dies and an unhandled exception happens. What is the cause of this?
private void ping()
{
comboBox3.Visible = false;
listBox2.Items.Clear();
// check the url if it is null
if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
{
listBox2.Items.Add("Please use valid IP or web address!!");
comboBox3.Visible = false;
coloring_red_tab4();
}
else
{
// do the ping
coloring_green_tab4();
for (int i = 0; i < numericUpDown1.Value; i++)
{
string s;
s = textBox1.Text;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
Ping p = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
//pingexception was unhalded (if the url wrong here is the error)
PingReply r = p.Send(s, timeout, buffer, options);
// if it's true url
if (r.Status == IPStatus.Success)
{
listBox2.Items.Add("Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n");
label91.Text = r.Address.ToString();
}
else
{
// just to know the ip for the website if they block the icmp protocol
listBox2.Items.Add(r.Status);
IPAddress[] ips;
ips = Dns.GetHostAddresses(textBox1.Text);
foreach (IPAddress ip in ips)
{
label91.Text = ip.ToString();
}
}
}
}
}
The exception is unhandled because you do not handle it. Whenever you call a .Net library method, you need to check its documentation to see what exceptions it throws, and decide which, if any, you want to handle at that level of code. Here is the relevant portion of the documentation for Ping.Send(), which I am including as an image so you will be able to recognize these sections going forward:
Notice that the documentation states that a PingException can occur if
An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.
Thus it's clear from the documentation that many errors from Ping() will be reported as thrown exceptions rather than reported by setting PingReply.Status != IPStatus.Success. So you need to modify your code to be something like the following:
public static bool TryPing(string hostNameOrAddress, out string pingStatusMessage, out string pingAddressMessage)
{
if (String.IsNullOrWhiteSpace(hostNameOrAddress))
{
pingStatusMessage = "Missing host name";
pingAddressMessage = "";
return false;
}
var data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
var buffer = Encoding.ASCII.GetBytes(data);
var timeout = 120;
using (var p = new Ping())
{
var options = new PingOptions();
options.DontFragment = true;
try
{
var r = p.Send(hostNameOrAddress, timeout, buffer, options);
if (r.Status == IPStatus.Success)
{
pingStatusMessage = "Ping to " + hostNameOrAddress.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n";
pingAddressMessage = r.Address.ToString();
return true;
}
else
{
// just to know the ip for the website if they block the icmp protocol
pingStatusMessage = r.Status.ToString();
var ips = Dns.GetHostAddresses(hostNameOrAddress);
pingAddressMessage = String.Join(",", ips.Select(ip => ip.ToString()));
return false;
}
}
catch (PingException ex)
{
pingStatusMessage = string.Format("Error pinging {0}: {1}", hostNameOrAddress, (ex.InnerException ?? ex).Message);
pingAddressMessage = hostNameOrAddress;
return false;
}
}
}
Here I have extracted a utility method from the user interface code and also properly disposed of the Ping instance after it is no longer needed.
Then
TryPing(#"www.google.com", out pingStatusMessage, out pingAddressMessage);
Gives
Ping to www.google.com[146.115.8.83] (Successful) Bytes =32 TTL=62 Response delay = 8 ms
While
TryPing(#"www.kdjf98rglkfgjldkfjgdl;fge8org.com", out pingStatusMessage, out pingAddressMessage);
Gives
Error pinging www.kdjf98rglkfgjldkfjgdl;fge8org.com: No such host is known
I'm trying to redirect input for powershell.exe remote execution.
And it gives me next output:
Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved.
Host receive failed 10054
So looks like it calls powershell, but next commands are not passed as input, nothing happens, so Process exited with timeout.
Why? Does PowerShell has some specific input, so it can't be launched like this? Any workarounds?
PS executed like next:
RemoteExecute.ExecutePowerShell(testPSName, testIp, testUserName, testPasswd);
ExecutePowerShell:
FTPTransfer.SendBinary(shellScriptName, ipaddress, userName, password); // This one sends script to remote system. Works OK.
string fullFilePath = "\"" + FTPTransfer.UploadDirectoryRootPath + shellScriptName + "\"";
string cmd;
using (StringWriter sw = new StringWriter())
{
//sw.WriteLine("powershell.exe"); // Tried launch remexec with cmd, and then pass powershell as first parameter. Results the same, as now, so no matter.
sw.WriteLine("Set-ExecutionPolicy RemoteSigned");
sw.WriteLine(fullFilePath);
cmd = sw.ToString();
}
result = ExecutePSCommandWithInput(cmd, ipaddress, userName, password);
ExecutePSCommandWithInput:
//command = cmd from ExecutePowerShell
string remexecCmd = "remexec.exe";
string remexecArgs = string.Format("{0} -q -t {1} -l {2} -p {3} powershell.exe 2>&1", ipaddress, timeout, userName, password);
result = Common.ExecuteCmdWithInput(remexecCmd, remexecArgs, command, out outp, timeout);
ExecuteCmdWithInput:
public static int ExecuteCmdWithInput(string mainCmd, string arguments, string commands, out string output, int timeout = 60000)
{
List<string> commandsArr = new List<string>();
using (StringReader sr = new StringReader(commands))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
commandsArr.Add(line);
line = sr.ReadLine();
}
}
return ExecuteCmdWithInput(mainCmd, arguments, commandsArr.ToArray(), out output, timeout);
}
public static int ExecuteCmdWithInput(string mainCmd, string arguments, string[] commands, out string output, int timeout = 60000)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = mainCmd;
p.StartInfo.Arguments = arguments;
p.Start();
using (StreamWriter inputWriter = p.StandardInput)
{
foreach(string line in commands)
{
inputWriter.WriteLine(line);
}
}
output = p.StandardOutput.ReadToEnd();
output += Environment.NewLine;
output += p.StandardError.ReadToEnd();
p.WaitForExit(timeout);
return p.ExitCode;
}
PowerShell doesn't use standard input or output, so I had to use workaround, or different implementation.
Solved like this:
string remexecArgs = string.Format("{0} -q -t {1} -l {2} -p {3} cmd 2>&1", ipaddress, timeout, userName, password);
and as input passed next:
using (StringWriter sw = new StringWriter())
{
sw.WriteLine("powershell.exe -Command Set-ExecutionPolicy RemoteSigned");
sw.WriteLine();
string logFilePath = "\"" + FTPTransfer.UploadDirectoryRootPath + shellScriptName + ".log\"";
sw.WriteLine("powershell.exe -File " + fullFilePath + " " + (pars ?? string.Empty) + "> " + logFilePath);
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("type " + logFilePath);
cmd = sw.ToString();
}
ExecuteOneCommandWithInput(cmd, ipaddress, userName, password, timeoutS);
Empty lines are nesesery, otherwise it stucks
And small hack added to process itself:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = mainCmd;
p.StartInfo.Arguments = arguments;
p.Start();
using (StreamWriter inputWriter = p.StandardInput)
{
foreach(string line in commands)
{
//Wait before next input in case when empty string passed
if (string.IsNullOrEmpty(line))
System.Threading.Thread.Sleep(1000 * 2);
inputWriter.WriteLine(line);
}
}
output = p.StandardOutput.ReadToEnd();
output += Environment.NewLine;
output += p.StandardError.ReadToEnd();
p.WaitForExit(timeout);
How can I scan (Symantec) a file for a virus while uploading, using Kendo UI Upload?
This question was answered on the Telerik forum:
The Kendo UI Upload does not include any file scanning capabilities
and frankly speaking, we have no intentions with this regard for the
time being. You can scan files via custom implementation or a tool
after saving them on the server, in the same fashion as you would do
that with a plain element.
You'll need to implement general server-side scanning of files, Kendo UI doesn't support it.
using com.symantec.scanengine.api;
public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
{
int bresult = 0;
string sReturn = string.Empty;
bresult = SaveFiles(files);
if (bresult == -2)
{
return Content("Corrupted");
}
else if (bresult == -1)
{
return Content("Incorrect");
}
else
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
public int SaveFiles(IEnumerable<HttpPostedFileBase> files)
{
int bresult = 0;
string sReturn = string.Empty;
if (ModelState.IsValid)
{
string sMessage = null;
try
{
foreach (var file in files)
{
// Some browsers send file names with full path. We only care about the file name.
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = System.IO.Path.GetFileName(file.FileName);
string fileExt = System.IO.Path.GetExtension(fileName);
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
bool IsValid = true;
if (IsValid)
{
file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
string scanIP = string.Empty;
int scanPort = Convert.ToInt16(ConfigurationManager.AppSettings["scanPort"]);
scanIP = ConfigurationManager.AppSettings["scanIPFromConfig"];
int scanResult = ScanUploads(scanIP, scanPort, fileName, fileBytes);
if (scanResult == -1)
{
bresult = -2;
}
else
{
//your logic to remove files
}
}
}
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message.ToString());
obj.ExceptionLogger(ex);
bresult = -1;
}
}
return bresult;
}
public int ScanUploads(string ScanIP, int scanPort, string valuetoscan, byte[] fileStream)
{
//try
//{
List<ScanEngineInfo> scanEnginesForScanning = new List<ScanEngineInfo>();
scanEnginesForScanning.Add(new ScanEngineInfo(ScanIP, scanPort));
//ScanEngineInfo scanEnginesForScanning = new ScanEngineInfo(ScanIP, scanPort);
ScanRequestManager requestManagerObj = new ScanRequestManager();
requestManagerObj.PrepareForScan(scanEnginesForScanning, 20000, 20);
//string scanPolicy = "policy";
string setScanPolicy = "DEFAULT";
dynamic scPolicy = (Policy)Enum.Parse(typeof(Policy), setScanPolicy);
StreamScanRequest testobjtoscan = requestManagerObj.CreateStreamScanRequest(scPolicy);
// byte[] array1 = null;
// int i = 0;
MemoryStream iStream = new MemoryStream();
ScanResult scanResult = default(ScanResult);
string scanresultClean = null;
int scanresultINFECTED = 0;
string scanresultcount = null;
string scanfilestatus = null;
iStream.Write(fileStream, 0, fileStream.Length);
testobjtoscan.Start(valuetoscan, "ScanFile");
testobjtoscan.Send(fileStream);
try
{
scanResult = testobjtoscan.Finish(iStream);
}
catch (Exception e)
{
throw;
}
scanfilestatus = Convert.ToString(scanResult.fileStatus.ToString());
scanresultcount = scanResult.threat.ToString();
scanresultClean = scanResult.fileStatus.ToString();
scanresultINFECTED = scanResult.totalInfection;
if (scanfilestatus != "CLEAN")
{
string errorMessage;
if(scanfilestatus == null)
{
errorMessage = "File Scan Status: null" + " Total Infection: " + scanResult.totalInfection + " connTriesInfo: ";
}
else{
errorMessage = "File Scan Status: " + scanfilestatus + " Total Infection: " + scanResult.totalInfection + " connTriesInfo: ";
}
foreach (var conninfo in scanResult.connTriesInfo)
{
errorMessage += " port: " + conninfo.port.ToString() + " problem encountered:" + conninfo.problemEncountered.ToString() + " scan host" + conninfo.scanHost.ToString();
}
iStream.Dispose();
Exception ex = new Exception("Symantec Virus Scan prevented file from being uploaded " + errorMessage);
obj.ExceptionLogger(ex);
return -1;
}
else
return 0;
}
public int ScanStream(string scanServer, int scanPort, string fileName, byte[] fileStream)
{
byte[] buffer = new byte[1024];
int iRx;
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string retDesc=string.Empty;
try
{
if (scanPort == 0)
scanPort = 1344;
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(scanServer);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, scanPort);
soc.Connect(remoteEndPoint);
if (soc.Connected)
{
string cmd = "RESPMOD icap://" + scanServer + ":" + scanPort + "/AVSCAN ICAP/1.0\n";
cmd = cmd + "Host: " + scanServer + ":" + scanPort + "\n";
cmd = cmd + "Allow: 204\n";
cmd = cmd + "Encapsulated: req-hdr=0, res-hdr=84, res-body=131\n";
cmd = cmd + "\n";
cmd = cmd + "GET http://”" + scanServer + "/" + fileName + " HTTP/1.1\n";
cmd = cmd + "Host: " + scanServer + "\n";
cmd = cmd + "\n";
cmd = cmd + "HTTP/1.1 200 OK\n";
cmd = cmd + "Transfer-Encoding: chunked\n";
cmd = cmd + "\n";
cmd = cmd + String.Format("{0:X2}", fileStream.Length) + "\n";
soc.Send(System.Text.Encoding.ASCII.GetBytes(cmd));
soc.Send(fileStream);
cmd = "\n";
cmd = cmd + "\n";
cmd = cmd + "0\n";
cmd = cmd + "\n";
soc.Send(System.Text.Encoding.ASCII.GetBytes(cmd));
while ((soc.Connected) && ((iRx = soc.Receive(buffer)) > 0))
{
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
retDesc = retDesc + szData;
}
soc.Close();
if (retDesc.Contains("X-Violations-Found:"))
return -1;
else
return 0;
}
else
return -1;
}
catch (Exception e)
{
if (soc != null)
soc.Close();
retDesc = e.Message;
obj.ExceptionLogger(e);
return -1;
}
}