Read() public method

public Read ( byte buffer, int offset, int count ) : int
buffer byte
offset int
count int
return int
Example #1
1
        static void Test()
        {
            // Connect as client to port 1300
            string server = "127.0.0.1";
            TcpClient client = new TcpClient(server, 1300);

            // Create a secure stream
            using (SslStream sslStream = new SslStream(client.GetStream(), false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
            {
                sslStream.AuthenticateAsClient(server);

                // ... Send and read data over the stream
                byte[] buffer = new byte[1024];
                int n = sslStream.Read(buffer, 0, 1024);


                string _message = System.Text.Encoding.UTF8.GetString(buffer, 0, n);
                System.Console.WriteLine("Client said: " + _message); 

            }

            // Disconnect and close the client
            client.Close();
        }
Example #2
1
        static void ProcessTcpClient(TcpClient client)
        {
            try
            {
                SslStream stream = new SslStream(client.GetStream());
                X509Certificate cert = new X509Certificate2(Certificate.CreateSelfSignCertificatePfx(
                    "CN=localhost", //host name
                    DateTime.Parse("2000-01-01"), //not valid before
                    DateTime.Parse("2099-01-01"), //not valid after
                    "mypassword"), "mypassword"); //password to encrypt key file)
                stream.AuthenticateAsServer(cert);

                byte[] requestBuffer = new byte[8192];
                int read = stream.Read(requestBuffer, 0, 8192);
                Array.Resize<byte>(ref requestBuffer, read);

                string request = Encoding.UTF8.GetString(requestBuffer);
                string requestedPath = request.Split('?')[0].Replace("GET ", "");

                Console.WriteLine(client.GetHashCode() + " => " + requestedPath);

                string response = "";

                if (requestedPath == "/gamepad/shardlist")
                {
                }
                else if (requestedPath == "/gamepad/lastshard")
                {
                }

                string header = "HTTP/1.1 200 OK\r\nDate: Fri, 10 Feb 2012 09:19:00 GMT\r\nServer: Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o\r\nContent-Length: " + response.Length + "\r\nContent-Type: text/html\r\n\r\n";

                byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                stream.Write(headerBytes);
                stream.Flush();
                stream.Write(responseBytes);
                stream.Flush();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured!\nMessage: " + e.Message + "\n" + e.StackTrace);
            }
        }
Example #3
1
        protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension)
        {
            ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
                new KeyValue("hash", b64hash),
                new KeyValue("type", type),
                new KeyValue("size", size.ToString())
            });
            string id = TicketManager.GenerateId();
            ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
                new KeyValue("id", id),
                new KeyValue("to", WhatsConstants.WhatsAppServer),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "w:m")
            }, media);
            this.uploadResponse = null;
            this.SendNode(node);
            int i = 0;
            while (this.uploadResponse == null && i <= 10)
            {
                i++;
                this.pollMessage();
            }
            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return res;
            }
            else
            {
                try
                {
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    Uri uri = new Uri(uploadUrl);

                    string hashname = string.Empty;
                    byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash));
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in buff)
                    {
                        sb.Append(b.ToString("X2"));
                    }
                    hashname = String.Format("{0}.{1}", sb.ToString(), extension);

                    string boundary = "zzXXzzYYzzXXzzQQ";

                    sb = new StringBuilder();

                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", to);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", this.phoneNumber);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
                    sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
                    string header = sb.ToString();

                    sb = new StringBuilder();
                    sb.AppendFormat("\r\n--{0}--\r\n", boundary);
                    string footer = sb.ToString();

                    long clength = size + header.Length + footer.Length;

                    sb = new StringBuilder();
                    sb.AppendFormat("POST {0}\r\n", uploadUrl);
                    sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
                    sb.AppendFormat("Host: {0}\r\n", uri.Host);
                    sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
                    sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
                    string post = sb.ToString();

                    TcpClient tc = new TcpClient(uri.Host, 443);
                    SslStream ssl = new SslStream(tc.GetStream());
                    try
                    {
                        ssl.AuthenticateAsClient(uri.Host);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    List<byte> buf = new List<byte>();
                    buf.AddRange(Encoding.UTF8.GetBytes(post));
                    buf.AddRange(Encoding.UTF8.GetBytes(header));
                    buf.AddRange(fileData);
                    buf.AddRange(Encoding.UTF8.GetBytes(footer));

                    ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);

                    //moment of truth...
                    buff = new byte[1024];
                    ssl.Read(buff, 0, 1024);

                    string result = Encoding.UTF8.GetString(buff);
                    foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("{"))
                        {
                            string fooo = line.TrimEnd(new char[] { (char)0 });
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            WaUploadResponse resp = jss.Deserialize<WaUploadResponse>(fooo);
                            if (!String.IsNullOrEmpty(resp.url))
                            {
                                return resp;
                            }
                        }
                    }
                }
                catch (Exception)
                { }
            }
            return null;
        }
        public void SendEmptyPushNotification(string deviceIdentifier, string thumbprint)
        {
            string server = "gateway.push.apple.com";
            using (TcpClient tcpClient = new TcpClient(server, 2195))
            {
                Trace.TraceInformation("Opening SSL Connection...");
                using (SslStream sslStream = new SslStream(tcpClient.GetStream()))
                {
                    try
                    {
                        X509Certificate2Collection certs = new X509Certificate2Collection();

                        Trace.TraceInformation("Adding certificate to connection...");
                        X509Certificate cert = GetAppleServerCert(thumbprint);
                        certs.Add(cert);

                        Trace.TraceInformation("Authenticating against the SSL stream...");
                        sslStream.AuthenticateAsClient(server, certs, SslProtocols.Default, false);
                    }
                    catch (AuthenticationException exp)
                    {
                        Trace.TraceError("Failed to authenticate to APNS - {0}", exp.Message);
                        return;
                    }
                    catch (IOException exp)
                    {
                        Trace.TraceError("Failed to connect to APNS - {0}", exp.Message);
                        return;
                    }

                    byte[] buf = new byte[256];
                    MemoryStream ms = new MemoryStream();
                    BinaryWriter bw = new BinaryWriter(ms);
                    bw.Write(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 });

                    byte[] deviceToken = HexToData(deviceIdentifier);
                    bw.Write(deviceToken);
                    
                    string msg = "{}";

                    bw.Write(new byte[] { 0, 2 });
                    bw.Write(msg.ToCharArray());
                    bw.Flush();

                    Trace.TraceInformation("Message sent. Closing stream...");

                    if (sslStream != null)
                    {
                        sslStream.Write(ms.ToArray());
                    }

                    sslStream.Flush();

                    byte[] response = new byte[6];
                    sslStream.Read(response, 0, 6);
                }
            }
        }
Example #5
0
 byte[] receiveData(System.Net.Sockets.TcpClient c, System.Net.Security.SslStream ssl)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         System.Threading.Thread.Sleep(2000);
         while (c.Available > 0)
         {
             byte[] buf = new byte[10000];
             int    len = ssl.Read(buf, 0, buf.Length);
             ms.Write(buf, 0, len);
         }
         return(ms.ToArray());
     }
 }
Example #6
0
        public static string ReadMessage(SslStream sslStream, TcpClient client)
        {
            byte[] buffer = new byte[256];
            int totalRead = 0;

            //read bytes until stream indicates there are no more
            do
            {
                int read = sslStream.Read(buffer, totalRead, buffer.Length - totalRead);
                totalRead += read;
                Console.WriteLine("ReadMessage: " + read);
            } while (client.GetStream().DataAvailable);

            return Encoding.Unicode.GetString(buffer, 0, totalRead);
        }
Example #7
0
            static string ReadMessage(SslStream sslStream)
            {
              
                byte[] buffer = new byte[2048];
                StringBuilder messageData = new StringBuilder();
                int bytes = -1;
                do
                {
                    bytes = sslStream.Read(buffer, 0, buffer.Length);                    
                    Decoder decoder = Encoding.UTF8.GetDecoder();
                    char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                    decoder.GetChars(buffer, 0, bytes, chars, 0);                    
                    messageData.Append(chars);
                    if (messageData.ToString().Contains(@"</Document>") == true)
                    {
                        break;
                    }
                } while (bytes != 0);

                return messageData.ToString();
            }            
Example #8
0
        public void Handle()
        {
            // Establish an SSL connection
            try
            {
                using (var sslStream = new SslStream(client.GetStream()))
                {

                    sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Default, true);

                    var buffer = new byte[2048];
                    var decoder = Encoding.ASCII.GetDecoder();
                    var chars = new char[buffer.Length];
                    while (true)
                    {
                        // Receive the request
                        var read = sslStream.Read(buffer, 0, buffer.Length);
                        decoder.GetChars(buffer, 0, read, chars, 0);
                        var str = new String(chars);

                        Trace.Write(str.Trim('\0'));

                        // Send the response
                        sslStream.Write(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Content-Length: 5\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Connection: close\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Hello"));
                    }
                }
            }
            catch(ThreadAbortException tae)
            {
                Trace.TraceInformation("Exiting Handler thread: " + Thread.CurrentThread);
            }
            catch (Exception ex)
            {
            }
        }
Example #9
0
        private string readMessage(SslStream stream)
        {
            byte[] buffer = new byte[2048];
            StringBuilder input = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = stream.Read(buffer, 0, buffer.Length);

                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                input.Append(chars);

                if (input.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            }
            while (bytes != 0);

            return input.ToString();
        }
Example #10
0
		private static byte[] ReadFromSslStream(SslStream stream, int max)
		{

			byte[] buffer = new byte[max];
			byte[] retval;
			if (stream.CanRead)
			{
				int bytesread = stream.Read(buffer, 0, max);
				retval = new byte[bytesread];

				using (MemoryStream ms = new MemoryStream(buffer))
				{
					ms.Read(retval, 0, bytesread);
				}
				return retval;
			}
			else
			{
				retval = new byte[0];
				return retval;
			}

		}
Example #11
0
        public override void HandleClient(object obj)
        {
            TcpClient client = (TcpClient)obj;

            byte[] message = new byte[10000];

            X509Certificate2 certificate = new X509Certificate2(Certificate.blazeServer, "123456");
            SslStream stream = new SslStream(client.GetStream(), false);

            try
            {
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Ssl3, false);
            }
            catch
            {
                client.Close();
            }

            Log.Info("Client connected to Blaze.");

            // increase number of connections
            _connections += 1;

            // add the client to dictionary
            ClientManager.AddClient(_connections, client.Client.RemoteEndPoint, stream);

            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = stream.Read(message, 0, message.Length);
                }
                catch
                {
                    Log.Info("Client disconnected from Blaze.");
                    client.Close();

                    var clientId = _connections;
                    var cl = ClientManager.GetClient(clientId);

                    Log.Info(string.Format("Deleting client {0} (disconnected).", clientId));

                    if (cl.type == ClientType.CLIENT_TYPE_DEDICATED_SERVER && cl.gameId != 0)
                    {
                        Log.Info("Deleting game from disconnected event");
                        Database.DeleteGame(cl.gameId);
                    }

                    ClientManager.clients.Remove(clientId);
                    break;
                }

                if (bytesRead == 0)
                {
                    break;
                }
                else
                {
                    // decode the packet
                    FireFrame fireFrame = new FireFrame(message);
                    Packet packet = fireFrame.Decode();

                    Router.HandleRequest(_connections, packet, stream);
                }
            }

            client.Close();
        }
Example #12
0
        public static string HTTPFetch(string url, string method,
            WebHeaderCollection headers, 
            byte[] streamBytes, 
            int contentLength, 
            out string[] responseFields,
            string contentType = "application/x-www-form-urlencoded",
            string requestAccept = null, 
            string host = null)
        {
            _active = true;
            try
            {
                var uri = new Uri(url);
                if (EndpointCallback != null) EndpointCallback(uri.AbsolutePath);
                if (string.IsNullOrEmpty(host)) host = uri.Host;

                string reqStr =
                    String.Format("{0} {1} HTTP/1.1\r\n", method, url) +
                    String.Format("Host: {0}\r\n", host) +
                    String.Format("Connection: Close\r\n");

                if (!IsNullOrWhiteSpace(requestAccept))
                    reqStr += String.Format("Accept: {0}\r\n", requestAccept);
                if (contentType != null)
                    reqStr += String.Format("Content-Type: {0}\r\n", contentType);

                if (headers != null)
                {
                    for (int i = 0; i < headers.Count; ++i)
                    {
                        string header = headers.GetKey(i);
                        foreach (string value in headers.GetValues(i))
                        {
                            reqStr += String.Format("{0}: {1}\r\n", header, value);
                        }
                    }
                }

                reqStr += String.Format("Content-Length: {0}\r\n", contentLength);
                reqStr += "\r\n";
                byte[] headerBytes = ToByteArray(reqStr);

                byte[] finalBytes = headerBytes;
                if (contentLength > 0)
                {
                    var requestBytes = new byte[headerBytes.Length + contentLength];
                    Buffer.BlockCopy(headerBytes, 0, requestBytes, 0, headerBytes.Length);
                    Buffer.BlockCopy(streamBytes, 0, requestBytes, headerBytes.Length, contentLength);
                    finalBytes = requestBytes;
                }

                string responseFromServer = "";
                responseFields = new string[] { };
                var tcpClient = new TcpClient();
                string responseStr = "";
                int responseLength = 0;

                if (url.ToLower().StartsWith("https"))
                {
                    //HTTPS
                    tcpClient.Connect(uri.Host, 443);
                    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => true);

                    //This has a bug on mono: Message	"The authentication or decryption has failed."
                    //Therefore unfortunately we have to ignore certificates.
                    using (var s = new SslStream(tcpClient.GetStream(), false,
                        new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => true)))
                    {
                        s.AuthenticateAsClient(uri.Host, null, SslProtocols.Tls, false);
                        if (UpstreamCallback != null && UpstreamCallbackRate > 0)
                        {
                            int i = 0;
                            while (i < finalBytes.Length)
                            {
                                if (!_active) throw new Exception("Halt");
                                if (i + _upstreamCallbackRate > finalBytes.Length)
                                {
                                    s.Write(finalBytes, i, finalBytes.Length - i);
                                    UpstreamCallback(contentLength, contentLength);
                                    break;
                                }
                                s.Write(finalBytes, i, (int)_upstreamCallbackRate);
                                i += (int)_upstreamCallbackRate;
                                UpstreamCallback(Math.Min(i, contentLength), contentLength);
                            }
                        }
                        else s.Write(finalBytes, 0, finalBytes.Length);
                        s.Flush();

                        while (true)
                        {
                            var responseBytes = new byte[8192];
                            int i = s.Read(responseBytes, 0, responseBytes.Length);
                            if (i == 0) break;
                            responseStr += Encoding.UTF8.GetString(responseBytes, 0, i);
                            responseLength += i;
                        }
                    }
                }
                else
                {
                    //HTTP
                    tcpClient.Connect(uri.Host, 80);
                    if (UpstreamCallback != null && UpstreamCallbackRate > 0)
                    {
                        var s = tcpClient.GetStream();
                        int i = 0;
                        while (i < finalBytes.Length)
                        {
                            if (!_active) throw new Exception("Halt");
                            if (i + _upstreamCallbackRate > finalBytes.Length)
                            {
                                s.Write(finalBytes, i, finalBytes.Length - i);
                                UpstreamCallback(contentLength, contentLength);
                                break;
                            }
                            s.Write(finalBytes, i, (int)_upstreamCallbackRate);
                            i += (int)_upstreamCallbackRate;
                            UpstreamCallback(Math.Min(i, contentLength), contentLength);
                        }
                    }
                    else tcpClient.Client.Send(finalBytes);

                    while (true)
                    {
                        var responseBytes = new byte[8192];
                        int i = tcpClient.Client.Receive(responseBytes);
                        if (i == 0) break;
                        responseStr += Encoding.UTF8.GetString(responseBytes, 0, i);
                        responseLength += i;
                    }
                }

                tcpClient.Close();

                var bodyPos = responseStr.IndexOf("\r\n\r\n");
                if (bodyPos >= 0)
                {
                    responseFields = responseStr.Substring(0, bodyPos).Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    bodyPos += 4;
                    responseFromServer = responseStr.Substring(bodyPos, responseStr.Length - bodyPos);
                }

                Debug.WriteLine(String.Format("Response from URL {0}:", url), "HTTPFetch");
                Debug.WriteLine(responseFromServer, "HTTPFetch");

                if (VerboseCallback != null)
                {
                    VerboseCallback(String.Format("Response from URL {0}:", url));
                    VerboseCallback(responseFromServer);
                }

                return responseFromServer;
            }
            catch (Exception e)
            {
                _active = false;
                throw e;
            }
        }
        public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config)
        {
            var url = config["onlineBatchUrl"];
            var port = int.Parse(config["onlineBatchPort"]);
            TcpClient tcpClient;
            SslStream sslStream;

            try
            {
                tcpClient = new TcpClient(url, port);
                sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null);
            }
            catch (SocketException e)
            {
                throw new LitleOnlineException("Error establishing a network connection", e);
            }

            try
            {
                sslStream.AuthenticateAsClient(url);
            }
            catch (AuthenticationException e)
            {
                tcpClient.Close();
                throw new LitleOnlineException("Error establishing a network connection - SSL Authencation failed", e);
            }

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Using XML File: " + xmlRequestFilePath);
            }

            using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
            {
                int bytesRead;

                do
                {
                    var byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length);

                    sslStream.Write(byteBuffer, 0, bytesRead);
                    sslStream.Flush();
                } while (bytesRead != 0);
            }

            var batchName = Path.GetFileName(xmlRequestFilePath);
            var destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);
            if (destinationDirectory != null && !Directory.Exists(destinationDirectory)) Directory.CreateDirectory(destinationDirectory);

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName);
            }

            using (var writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
            {
                int bytesRead;

                do
                {
                    var byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length);

                    writeFileStream.Write(byteBuffer, 0, bytesRead);
                } while (bytesRead > 0);
            }

            tcpClient.Close();
            sslStream.Close();

            return xmlResponseDestinationDirectory + batchName;
        }
Example #14
0
 /// <summary>
 /// 注意:此函数可能产生死循环
 /// </summary>
 /// <param name="ssl"></param>
 /// <returns></returns>
 static byte[] ParseSslResponse(SslStream ssl)
 {
     //没有指定协议头,尝试读取至</html>
     ArrayList array = new ArrayList();
     StringBuilder bulider = new StringBuilder();
     int length = 0;
     while (true)
     {
         byte[] buff = new byte[1024];
         int len = ssl.Read(buff, 0, buff.Length);
         if (len > 0)
         {
             length += len;
             byte[] reads = new byte[len];
             Array.Copy(buff, 0, reads, 0, len);
             array.Add(reads);
             bulider.Append(Encoding.Default.GetString(reads));
         }
         string temp = bulider.ToString();
         if (temp.ToUpper().Contains("</HTML>"))
         {
             break;
         }
     }
     byte[] bytes = new byte[length];
     int index = 0;
     for (int i = 0; i < array.Count; i++)
     {
         byte[] temp = (byte[])array[i];
         Array.Copy(temp, 0, bytes,
             index, temp.Length);
         index += temp.Length;
     }
     return bytes;
 }
Example #15
0
 private static string QuickRead(SslStream sslStream)
 {
     _readBuffer = new byte[ConfigurationSupport.bufferSize];
     int offset = 0;
     int count = 0;
     StringBuilder builder = new StringBuilder();
     if (sslStream != null)
     {
         do
         {
             count = sslStream.Read(_readBuffer, 0, _readBuffer.Length);
             System.Text.Decoder decoder = Encoding.ASCII.GetDecoder();
             char[] chars = new char[decoder.GetCharCount(_readBuffer, 0, count)];
             decoder.GetChars(_readBuffer, 0, count, chars, 0);
             builder.Append(chars);
             if (builder.ToString().IndexOf("\n") != -1)
             {
                 break;
             }
         }
         while (count != 0);
     }
     else
     {
         do
         {
             int num3 = _client.GetStream().Read(_readBuffer, offset, _readBuffer.Length - offset);
             offset += num3;
         }
         while (_client.GetStream().DataAvailable);
         builder.Append(Encoding.ASCII.GetString(_readBuffer, 0, offset));
     }
     return builder.ToString().TrimEnd(new char[] { '\r', '\n' });
 }
Example #16
0
		public void ServiceClient(object remote)
		{
			TcpClient client = (TcpClient)remote;
			try
			{
				String input = "";
				Byte[] data = new Byte[8192];
				Byte[] send = null;
				String[] returnValue = null;
				Int32 bytesRec = 0;
				Int32 marker = -1;
				Boolean escape = false;
				Boolean tls = false;

				send = Encoding.UTF8.GetBytes(String.Format("# munin node at {0}\n", System.Environment.MachineName));
				NetworkStream stream = client.GetStream();
				stream.Write(send, 0, send.Length);

				while (!escape && !tls && ((bytesRec = stream.Read(data, 0, 8192)) > 0))
				{
					input += Encoding.UTF8.GetString(data, 0, bytesRec);
					NodeService.log("Input: " + input);
					while (!escape && ((marker = input.IndexOfAny(lineBreaks)) > -1))
					{
						String command = input.Substring(0, marker);
						input = input.Substring(marker + 1);
						NodeService.log("Received: " + command);

						if (processDelegate != null)
						{
							returnValue = processDelegate(command);
							if (returnValue != null)
							{
								foreach (String s in returnValue)
								{
									NodeService.log(String.Format("Sending ({0}): {1}", s.Length, s));
									stream.Write(Encoding.UTF8.GetBytes(s), 0, s.Length);
									tls = s.Equals("TLS OK\n");
								}
							}
							else
							{
								escape = true;
							}
						}
					}
				}
				if (tls)
				{
					SslStream sslStream = new SslStream(stream, false);
					NodeService.log("SSL stream opened");
					try
					{
						try
						{
							sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);
						}
						catch (Exception ex)
						{
							NodeService.log(ex.Message);
						}
						while (!escape && ((bytesRec = sslStream.Read(data, 0, 8192)) > 0))
						{
							input += Encoding.UTF8.GetString(data, 0, bytesRec);
							NodeService.log("TLS Input: " + input);
							while (!escape && ((marker = input.IndexOfAny(lineBreaks)) > -1))
							{
								string command = input.Substring(0, marker);
								input = input.Substring(marker + 1);
								NodeService.log("TLS Received: " + command);

								if (processDelegate != null)
								{
									returnValue = processDelegate(command);
									if (returnValue != null)
									{
										foreach (String s in returnValue)
										{
											NodeService.log(String.Format("TLS Sending ({0}): {1}", s.Length, s));
											sslStream.Write(Encoding.UTF8.GetBytes(s));
										}
									}
									else
									{
										escape = true;
									}
								}
							}
						}
					}
					catch (AuthenticationException e)
					{
						NodeService.log(String.Format("Exception: {0}", e.Message));
						if (e.InnerException != null)
						{
							NodeService.log(String.Format("Inner exception: {0}", e.InnerException.Message));
						}
					}
					finally
					{
						// The client stream will be closed with the sslStream
						// because we specified this behavior when creating
						// the sslStream.
						sslStream.Close();
					}
				}

			}
			catch (Exception)
			{
				NodeService.log("Connection Error");
			}
			finally
			{
				try
				{
					client.Close();
				}
				catch (Exception) { }
				NodeService.log("Connection Closed");
			}
		}
Example #17
0
 /// <summary>
 /// 解析 Ssl Response
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="ssl"></param>
 /// <param name="args"></param>
 /// <param name="certificates"></param>
 /// <returns></returns>
 private static byte[] ParseSslResponse(IPEndPoint endpoint, SslStream ssl, HttpArgs args, X509CertificateCollection certificates)
 {
     //尝试4秒时间读取协议头
     CancellationTokenSource source = new CancellationTokenSource();
     Task<string> myTask = Task.Factory.StartNew<string>(HttpClient.ReadHeaderProcess, ssl, source.Token);
     if (myTask.Wait(4000))
     {
         string header = myTask.Result;
         if (header.StartsWith("HTTP/1.1 302"))
         {
             int start = header.IndexOf("LOCATION", StringComparison.OrdinalIgnoreCase);
             if (start > 0)
             {
                 string temp = header.Substring(start, header.Length - start);
                 string[] sArry = Regex.Split(temp, "\r\n");
                 args.Url = sArry[0].Remove(0, 10);
                 //注意:302协议需要重定向
                 return Get(endpoint, args, certificates);
             }
         }
         //继续读取内容
         else if (header.StartsWith("HTTP/1.1 200"))
         {
             int start = header.IndexOf("CONTENT-LENGTH", StringComparison.OrdinalIgnoreCase);
             if (start > 0)
             {
                 string temp = header.Substring(start, header.Length - start);
                 string[] sArry = temp.Split(new char[] { '\r', '\n', ' ', ':' }, StringSplitOptions.RemoveEmptyEntries);
                 int content_length;
                 if (sArry.Length > 1 && Int32.TryParse(sArry[1], out content_length))
                 {
                     byte[] bytes = new byte[content_length];
                     if (ssl.Read(bytes, 0, content_length) > 0)
                     {
                         return bytes;
                     }
                 }
             }
             else
             {
                 //不存在Content-Length协议头
                 return HttpClient.ParseResponse(ssl);
             }
         }
         else
         {
             return Encoding.UTF8.GetBytes(header);
         }
     }
     else
     {
         //超时的话,别忘记取消任务哦
         source.Cancel();
     }
     return null;
 }
Example #18
0
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte [] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }
Example #19
0
        /// <summary>
        /// Performs performQuery() on Ews, asking how a doc processed.
        /// </summary>
        /// <param name="submittedFile">File to read parameters from</param>
        /// <param name="callerType">this.GetType() - since we're static, we need a way to load embedded resources</param>
        /// <returns>The XML as string as the webservice returns it</returns>
        public static string GetProcessingResult(XmlDocument submittedFile, Type callerType, string username, string password)
        {
            if (submittedFile == null)
                return null;
            // fill in query template
            Stream stream = callerType.Assembly.GetManifestResourceStream("XtbCnb2.performQueryTemplate.txt");
            StreamReader sr = new StreamReader(stream);
            string query = sr.ReadToEnd();
            sr.Close();

            query = query.Replace("***USERNAME***", username);
            query = query.Replace("***PASSWORD***", password);
            XmlNode node = submittedFile.SelectSingleNode("/VYDANI/IDENTIFIKACE-VYKAZU/VYSKYT/STAV-KE-DNI");
            // yyyymmdd -> dd.mm.yyyy
            string s = node.InnerText;
            query = query.Replace("***OBDOBIV***", s.Substring(6,2) + "." + s.Substring(4,2) + "." + s.Substring(0,4));
            node = submittedFile.SelectSingleNode("/VYDANI/IDENTIFIKACE-VYKAZU/VYSKYT/SUBJEKT");
            query = query.Replace("***SUBJEKTV***", node.InnerText);
            node = submittedFile.SelectSingleNode("/VYDANI/IDENTIFIKACE-VYKAZU/DATOVY-SOUBOR");
            s = node.InnerText;
            int pos = s.IndexOf('.');
            if (pos > 0)
                s = s.Substring(0, pos);
            query = query.Replace("***DATOVY-SOUBOR***", s);

            string t = query;
            t = t.Replace(password, "[[[CENSORED]]]");
            string fnameForLog = "Q" + CnbData.ConstructCisloVydani().ToString() + ".xml";
            Log.LogAsText("User " + username + " querying document status via document " + fnameForLog);
            Log.LogAsFile(t, fnameForLog);

            query = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(query), Base64FormattingOptions.InsertLineBreaks);

            // fill in SOAP template
            stream = callerType.Assembly.GetManifestResourceStream("XtbCnb2.QuerySOAPTemplate.txt");
            sr = new StreamReader(stream);
            string soap = sr.ReadToEnd();
            sr.Close();

            soap = soap.Replace("***DATA-LENGTH***", (query.Length + 1).ToString());                    // +1 for \n
            soap = soap.Replace("***DATA***", query);

            // fill in total length
            byte[] tData = System.Text.Encoding.UTF8.GetBytes(soap);

            byte lastByte = 0;
            for (pos = 0; pos < tData.Length; pos++)
            {
                if (lastByte == 10 && tData[pos] == 10)
                    break;

                lastByte = tData[pos];
            }

            int totalLength = tData.Length - pos - 1;
            soap = soap.Replace("***TOTAL-LENGTH***", totalLength.ToString());

            // set up connection to webservice (we can't do this the comfy way as MS doesn't support SwA)
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };

            try
            {
                TcpClient client = new TcpClient(machineName, 443);
                client.SendTimeout = 2 * 60 * 1000;
                SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                sslStream.AuthenticateAsClient(machineName, null, SslProtocols.Ssl2 | SslProtocols.Ssl3, false);
                byte[] messsage = System.Text.Encoding.UTF8.GetBytes(soap);

            //                File.WriteAllBytes(@"C:\projekty\XtbCnb2\XtbCnb2\Tomas Drabek\soap.bin", messsage);

                // send request to ws
                sslStream.Write(messsage);
                sslStream.Flush();

                // read ws response
                byte[] buffer = new byte[2048];
                StringBuilder messageData = new StringBuilder();
                int bytes = -1;
                do
                {
                    bytes = sslStream.Read(buffer, 0, buffer.Length);

                    if (bytes == 0)
                        break;

                    Decoder decoder = Encoding.UTF8.GetDecoder();
                    char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                    decoder.GetChars(buffer, 0, bytes, chars, 0);
                    messageData.Append(chars);
                } while (bytes != 0);

                client.Close();

                // get the response part we care about
                string rawMessage = messageData.ToString();
                rawMessage = rawMessage.Replace("\r\n", "\n");

                string resfname = "S" + CnbData.ConstructCisloVydani().ToString() + ".txt";
                Log.LogAsText("Response recorded as file " + resfname);
                Log.LogAsFile(rawMessage, resfname);

                // check HTTP result code
                Regex checkHeader = new Regex("HTTP/1.. 200.*");
                if (!checkHeader.IsMatch(rawMessage))
                    throw new Exception("Webservice returned the following raw error:\n" + rawMessage);

                Regex regex = new Regex(".*?Content-Type: .*? boundary.?=.?\"(.*?)\".*");
                Match match = regex.Match(rawMessage);
                string boundary = match.Groups[1].Value;

                pos = rawMessage.IndexOf(boundary);
                pos = rawMessage.IndexOf(boundary, pos + boundary.Length);
                pos = rawMessage.IndexOf(boundary, pos + boundary.Length);
                pos += boundary.Length;
                int partStart = pos;
                partStart = rawMessage.IndexOf("\n\n", partStart) + 2;
                int partEnd = rawMessage.IndexOf(boundary, pos) - 2;                                    // mime prepends 2 minuses, we don't want them
                string b64Message = rawMessage.Substring(partStart, partEnd - partStart);

                // decode the part
                byte[] decoded = null;

                try
                {
                    decoded = Convert.FromBase64String(b64Message);
                    return System.Text.Encoding.UTF8.GetString(decoded);
                }
                catch (Exception)
                {
                    return b64Message;
                }
            }
            catch (Exception e)
            {
                string msg = string.Format("Exception type: {0}, exception info: {1}", e.ToString(), e.Message);
                if (e.InnerException != null)
                    msg += string.Format("\n\nInner exception type: {0}, exception info: {1}", e.InnerException.ToString(), e.InnerException.Message);

                MessageBox.Show(msg, "Exception Encountered");
                return null;
            }
        }
        // Reads all incoming strings up to the line containing the specified tag.
        private bool ReadResponse(string tag, out string response, SslStream stream)
        {
            int byteCount;
            response = string.Empty;
            bool? tagOk = null;
            string pattern = "^" + tag + " (?<ok>[a-zA-Z]+).*\r\n";
            Match m;

            while (!tagOk.HasValue)
            {
                try
                {
                    byteCount = stream.Read(this.buffer, 0, this.buffer.Length);
                    byte[] data = new byte[byteCount];
                    Array.Copy(this.buffer, data, byteCount);
                    response += Encoding.ASCII.GetString(data);
                }
                catch (Exception e)
                {
                    Error = e.Message;
                    return false;
                }

                m = Regex.Match(response, pattern, RegexOptions.Multiline);
                if (m.Success)
                {
                    if (m.Groups["ok"].ToString() == "OK")
                    {
                        tagOk = true;
                    }
                    else
                    {
                        tagOk = false;
                    }
                }
            }

            // Debug.Write("Response:\n" + response);
            return (bool)tagOk;
        }
        public void send_message()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = new StringEncoder();
            var decoder = new StringDecoder();
            object expected = null;

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);
            sut.Send("Hello world");

            var buf = new byte[65535];
            var tmp = stream.Read(buf, 0, 65535);
            var actual = Encoding.ASCII.GetString(buf, 4, tmp-4); // string encoder have a length header.
            actual.Should().Be("Hello world");
        }
Example #22
0
        public string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            String messageData = "";
            byte[] buffer = new byte[2048];

            do
            {
                int read = sslStream.Read(buffer, 0, buffer.Length);

                // Convert the bytes to a string
                messageData += new String(Encoding.UTF8.GetChars(buffer), 0, read);

                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (sslStream.CanRead);

            return messageData.ToString();
        }
        public virtual string socketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<String, String> config)
        {
            string url = config["onlineBatchUrl"];
            int port = Int32.Parse(config["onlineBatchPort"]);
            TcpClient tcpClient = null;
            SslStream sslStream = null;

            try
            {
                tcpClient = new TcpClient(url, port);
                sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            }
            catch (SocketException e)
            {
                throw new LitleOnlineException("Error establishing a network connection", e);
            }

            try
            {
                sslStream.AuthenticateAsClient(url);
            }
            catch (AuthenticationException)
            {
                tcpClient.Close();
                throw new LitleOnlineException("Error establishing a network connection - SSL Authencation failed");
            }

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Using XML File: " + xmlRequestFilePath);
            }

            using (FileStream readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
            {
                int bytesRead = -1;
                byte[] byteBuffer;

                do
                {
                    byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length);

                    sslStream.Write(byteBuffer, 0, bytesRead);
                    sslStream.Flush();
                } while (bytesRead != 0);
            }

            string batchName = Path.GetFileName(xmlRequestFilePath);
            string destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);
            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            if ("true".Equals(config["printxml"]))
            {
                Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName);
            }

            using (FileStream writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
            {
                char[] charBuffer;
                byte[] byteBuffer;
                int bytesRead = 0;

                do
                {
                    charBuffer = new char[1024];
                    byteBuffer = new byte[1024 * sizeof(char)];
                    bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length);
                    charBuffer = Encoding.UTF8.GetChars(byteBuffer);

                    writeFileStream.Write(byteBuffer, 0, bytesRead);
                } while (bytesRead > 0);
            }

            tcpClient.Close();
            sslStream.Close();

            return xmlResponseDestinationDirectory + batchName;
        }
Example #24
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                (sender, cert, chain, sslErrs) => { return true; },
                (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);

            //Set up
            byte[] buffer = new byte[38];
            int recd = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                try
                {

                    //Get our seconds since 1970 ?
                    byte[] bSeconds = new byte[4];
                    byte[] bDeviceToken = new byte[32];

                    Array.Copy(buffer, 0, bSeconds, 0, 4);

                    //Check endianness
                    if (BitConverter.IsLittleEndian)
                        Array.Reverse(bSeconds);

                    int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                    //Add seconds since 1970 to that date, in UTC and then get it locally
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds).ToLocalTime();

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!settings.FeedbackTimeIsUTC)
                        timestamp = timestamp.ToLocalTime();

                    //Now copy out the device token
                    Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                    var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                    //Make sure we have a good feedback tuple
                    if (deviceToken.Length == 64
                        && timestamp > minTimestamp)
                    {
                        //Raise event
                        RaiseFeedbackReceived(deviceToken, timestamp);
                    }

                }
                catch { }

                //Clear our array to reuse it
                Array.Clear(buffer, 0, buffer.Length);

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }
        }
        private byte[] ReadMessage(SslStream sslStream)
        {
            byte[] sizeBytes = new byte[4];
            sslStream.Read (sizeBytes, 0, sizeBytes.Length);

            if (BitConverter.IsLittleEndian)
                Array.Reverse (sizeBytes);

            uint size = BitConverter.ToUInt32 (sizeBytes, 0);

            byte[] buffer = new byte[size];
            sslStream.Read (buffer, 0, buffer.Length);

            return buffer;
        }
Example #26
0
        /// <summary>
        ///   Establishes the connection with a cosign server.
        /// </summary>
        /// <returns>true is connection is established</returns>
        public bool EstablishConnection()
        {
            // Create a TCP/IP client socket.
            // serverIP is the host running the server application.
            var buffer = new byte[256];
            int bytes;
            string receivedData;

            try
            {
                _client = new TcpClient(ServerIpAddress.ToString(), _serverPort) { ReceiveTimeout = 1000 };
            }
            catch (Exception ex)
            {
                _logger.Error("Could not connect to the server", ex);
                return false;
            }

            try
            {
                _logger.Trace("Client connected.");
                NetworkStream stream = _client.GetStream();

                // Read in first message from cosign server
                // Need to verify here if response is valid
                bytes = stream.Read(buffer, 0, buffer.Length);
                receivedData = Encoding.UTF8.GetString(buffer, 0, bytes);

                if (receivedData.Substring(0, 3) != "220")
                {
                    _logger.Error("Server did not return 220, returned : {0}", receivedData);
                    return false;
                }
                if (receivedData.Substring(4, 1) != "2")
                {
                    _logger.Error("Server running wrong version of cosign : {0}", receivedData);
                    return false;
                }
                _logger.Trace("Received: {0}", receivedData);

                // Initiate Secure negotiation
                _logger.Trace("Sending {0}", "STARTTLS 2\r\n");
                byte[] data = Encoding.UTF8.GetBytes("STARTTLS 2\r\n");
                stream.Write(data, 0, data.Length);

                // See if negotiation is started
                buffer = new byte[256];
                bytes = stream.Read(buffer, 0, buffer.Length);
                receivedData = Encoding.UTF8.GetString(buffer, 0, bytes);
                _logger.Trace("Received: {0}", receivedData);
            }
            catch (Exception ex)
            {
                _logger.Error("Exception while communicating with server", ex);
                _client.Close();
                return false;
            }

            // Create an SSL stream that will close the client's stream.
            _sslStream = new SslStream(_client.GetStream(), false, ValidateServerCertificate, null);

            // The server name must match the name on the server certificate.
            try
            {
                // Determine if we should check for cert revocation
                _sslStream.AuthenticateAsClient(_serverName, _certificateCollection, SslProtocols.Default, false);
            }
            catch (AuthenticationException e)
            {
                _logger.Error("Could not Authenticate with server - {0}", e.Message);
                _logger.Trace("Authentication failed - closing the connection.");
                _client.Close();
                return false;
            }
            catch (Exception ex)
            {
                _logger.Error("Exception while trying to authenticate secure connection with server", ex);
                _client.Close();
                return false;
            }

            // Check to see if negotiation was successful
            try
            {
                buffer = new byte[256];
                bytes = _sslStream.Read(buffer, 0, buffer.Length);
                receivedData = Encoding.UTF8.GetString(buffer, 0, bytes);
                _logger.Trace("Received: {0}", receivedData);
                // -- Changed in Cosign 3.2.0 to code 220, not sure if bug
                if (receivedData.Substring(0, 3) != "220")
                {
                    _logger.Error("Server did not return a success in TLS negotiation - {0}", receivedData);
                    _client.Close();
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Exception while trying to establish secure connection with server", ex);
                _client.Close();
                return false;
            }
            return true;
        }
        private string ReadMessage(SslStream sslStream)
        {
            byte[ ] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder ();
            int bytes = -1;
            do {
                bytes = sslStream.Read (buffer, 0, buffer.Length);

                Decoder decoder = Encoding.ASCII.GetDecoder ();
                char[ ] chars = new char[decoder.GetCharCount (buffer, 0, bytes)];
                decoder.GetChars (buffer, 0, bytes, chars, 0);
                messageData.Append (chars);

                // Check for EOF.
                if (bytes < buffer.Length) {
                    bytes = 0;
                    return messageData.ToString ();
                }

                buffer = new byte[2048]; //clear cruft
            } while (bytes != 0);

            return messageData.ToString ();
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            string transactionModeStr = string.Empty;
            if (transactionMode == TransactMode.Authorize)
                transactionModeStr = "AUTHORIZATION";
            else if (transactionMode == TransactMode.AuthorizeAndCapture)
                transactionModeStr = "AUTHORIZATION_CAPTURE";
            else
                throw new NopException("Not supported transaction mode");

            // This is the standard information that is needed to connect to PayJunction
            string server = GetUrl();
            int port = 443;
            SslStream stream = null;

            // Encode Data Values
            string encodedPJLogin = Encode("dc_logon", pjlogon);
            string encodedPJPassword = Encode("dc_password", pjpassword);
            string encodedFirstname = Encode("dc_first_name", paymentInfo.BillingAddress.FirstName);
            string encodedLastname = Encode("dc_last_name", paymentInfo.BillingAddress.LastName);
            string encodedCCNumber = Encode("dc_number", paymentInfo.CreditCardNumber);
            string encodedExpMonth = Encode("dc_expiration_month", paymentInfo.CreditCardExpireMonth.ToString("D2"));
            string encodedExpYear = Encode("dc_expiration_year", paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2));
            string encodedCVVCode = Encode("dc_verification_number", paymentInfo.CreditCardCvv2);
            string encodedAddress = Encode("dc_address", paymentInfo.BillingAddress.Address1);
            string encodedCity = Encode("dc_city", paymentInfo.BillingAddress.City);
            string encodedZipCode = Encode("dc_zipcode", paymentInfo.BillingAddress.ZipPostalCode);
            string encodedTransType = Encode("dc_transaction_type", transactionModeStr);
            string encodedAmount = Encode("dc_transaction_amount", paymentInfo.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            string encodedVersion = Encode("dc_version", "1.2");

            // Concatenate Encoded Transaction String
            string transactioninfo = "POST /quick_link?" + encodedPJLogin + "&" + encodedPJPassword + "&" + encodedFirstname + "&" + encodedLastname + "&" + encodedCCNumber + "&" + encodedExpMonth + "&" + encodedExpYear + "&" + encodedCCNumber + "&" + encodedAddress + "&" + encodedCity + "&" + encodedZipCode + "&" + encodedTransType + "&" + encodedAmount + "&" + encodedVersion + " \r\n\r\n";

            try
            {
                // Instantiate a TcpClient with the server and port
                TcpClient client = new TcpClient(server, port);
                // Convert the data to send into a byte array
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(transactioninfo);
                // Specify the callback function that will act as the validation delegate.
                RemoteCertificateValidationCallback callback = new
                    // This lets you inspect the certificate to see if it meets your validation requirements.
                RemoteCertificateValidationCallback(OnCertificateValidation);
                // Instantiate an SslStream with the NetworkStream returned from the TcpClient.
                stream = new SslStream(client.GetStream(), false, callback);
                // As a client, you can authenticate the server and validate the results using the SslStream.
                // This is the host name of the server you are connecting to, which may or may not be the name used to connect to the server when TcpClient is instantiated.
                stream.AuthenticateAsClient(server);
                // Send the message to the server.
                stream.Write(data, 0, data.Length);
                // Buffer to hold data returned from the server.
                data = new Byte[2048];
                // Read the response from the server up to the size of the buffer.
                int bytes = stream.Read(data, 0, data.Length);
                Console.WriteLine(bytes);
                // Convert the received bytes into a string
                string responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                // Create an Array "keyValue" that contains the response
                string[] keyValue = responseData.Split(Convert.ToChar(28));
                Dictionary<string, string> keyValueDic = new Dictionary<string, string>();
                foreach (string key in keyValue)
                {
                    string str1 = key.Split(new char[] { '=' })[0];
                    string str2 = key.Split(new char[] { '=' })[1];
                    keyValueDic.Add(str1, str2);
                }

                string dc_response_code = string.Empty;
                if (keyValueDic.ContainsKey("dc_response_code"))
                {
                    dc_response_code = keyValueDic["dc_response_code"];
                }
                string dc_response_message = string.Empty;
                if (keyValueDic.ContainsKey("dc_response_message"))
                {
                    dc_response_message = keyValueDic["dc_response_message"];
                }

                if (dc_response_code == "00" || dc_response_code == "85")
                {
                    string dc_transaction_id = string.Empty;
                    if (keyValueDic.ContainsKey("dc_transaction_id"))
                    {
                        dc_transaction_id = keyValueDic["dc_transaction_id"];
                    }
                    if (transactionMode == TransactMode.Authorize)
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        processPaymentResult.AuthorizationTransactionId = dc_transaction_id;
                    }
                    else
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        processPaymentResult.CaptureTransactionId = dc_transaction_id;
                    }
                }
                else
                {
                    processPaymentResult.Error = string.Format("Error: {0}. {1}", dc_response_message, dc_response_code);
                    processPaymentResult.FullError = string.Format("Error: {0}. {1}", dc_response_message, dc_response_code);
                }
            }
            catch (Exception exc)
            {
                processPaymentResult.Error = string.Format("Error: {0}", exc.Message);
                processPaymentResult.FullError = string.Format("Error: {0}", exc.ToString());
            }
            finally
            {
                // Make sure that the SslStream is closed.
                if (stream != null)
                    stream.Close();
            }
        }
Example #29
0
        public MFTestResults RunServer()
        {
            MFTestResults testResult = MFTestResults.Fail;
            SslStream sslStream = null;

            try
            {
                sslServer = new TcpListener(ipAddress, port);

                // Start listening for client requests.
                sslServer.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[2048];
                String data = null;

                // Start Listening for a connection.
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = sslServer.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                sslStream = new SslStream(client.GetStream());

                sslStream.AuthenticateAsServer(certificate, clientCertificateRequired, enabledSslProtocols, false);

                TestUtilities.PrintSslStreamProperties(sslStream);

                int i = 0;
                // Loop to receive all the data sent by the client.
                while ((i = sslStream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a string.
                    // The encoding used is application specific.
                    data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);

                    byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);

                    // Send back a response.
                    sslStream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent:     {0}", data);
                }
                testResult = MFTestResults.Pass;
            }
            catch (SocketException e)
            {
                if (expectedException)
                    testResult = MFTestResults.Pass;

                Console.WriteLine("SocketException in StartServer(): " + e.ToString());
                Console.WriteLine("ErrorCode: " + e.ErrorCode.ToString());
            }
            catch (Exception e)
            {
                if (expectedException)
                    testResult = MFTestResults.Pass;

                Console.WriteLine("Exception in StartServer(): " + e.ToString());
            }
            finally
            {
                if (sslStream != null)
                {
                    sslStream.Dispose();
                    sslStream = null;
                }
                if (sslServer != null)
                {
                    sslServer.Stop();
                    sslServer = null;
                }
            }

            return testResult;
        }
Example #30
0
 /// <summary>
 /// 解析 Ssl Response
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="ssl"></param>
 /// <param name="args"></param>
 /// <param name="certificates"></param>
 /// <returns></returns>
 private static byte[] ParseSslResponse(IPEndPoint endpoint,
     SslStream ssl,
     HttpArgs args,
     X509CertificateCollection certificates)
 {
     //尝试10秒时间读取协议头
     CancellationTokenSource source = new CancellationTokenSource();
     Task<string> myTask = Task.Factory.StartNew<string>(
         new Func<object, string>(ReadSslHeaderProcess),
         ssl,
         source.Token);
     if (myTask.Wait(10000))
     {
         string header = myTask.Result;
         if (header.StartsWith("HTTP/1.1 302"))
         {
             int start = header
                 .ToUpper().IndexOf("LOCATION");
             if (start > 0)
             {
                 string temp = header.Substring(start, header.Length - start);
                 string[] sArry = Regex.Split(temp, "\r\n");
                 args.Url = sArry[0].Remove(0, 10);
                 return Get(endpoint, args, certificates);  //注意:302协议需要重定向
             }
         }
         else if (header.StartsWith("HTTP/1.1 200"))  //继续读取内容
         {
             int start = header
                    .ToUpper().IndexOf("CONTENT-LENGTH");
             int content_length = 0;
             if (start > 0)
             {
                 string temp = header.Substring(start, header.Length - start);
                 string[] sArry = Regex.Split(temp, "\r\n");
                 content_length = Convert.ToInt32(sArry[0].Split(':')[1]);
                 if (content_length > 0)
                 {
                     byte[] bytes = new byte[content_length];
                     if (ssl.Read(bytes, 0, bytes.Length) > 0)
                     {
                         return bytes;
                     }
                 }
             }
             else
             {
                 //不存在Content-Length协议头
                 return ParseSslResponse(ssl);
             }
         }
         else
         {
             return Encoding.Default.GetBytes(header);
         }
     }
     else
     {
         source.Cancel();  //超时的话,别忘记取消任务哦
     }
     return null;
 }
        /// <summary>
        /// Uses a TCPClient and SSLStream to perform a POST.
        /// </summary>
        /// <param name="requestUrl">URL that the POST must be directed to.</param>
        /// <param name="body">Message that is to be sent.</param>
        /// <param name="user">UserId in your Zeep System. Only required if your sending a Single Message to a User.
        /// Otherwise, just send a string.Empty.</param>
        /// <returns>Response from the server. (although it will write the response to console)</returns>
        public static string SendSMS(string requestUrl, string body, string user)
        {
            string parameters     = "";
            string requestHeaders = "";
            string responseData   = "";

            // FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
            string http_date = DateTime.UtcNow.ToString("r");

            // Clean the text to send
            body = HttpUtility.UrlEncode(body, System.Text.Encoding.UTF8);

            if (user.Length > 0)
            {
                parameters += "user_id=" + user + "&";
            }
            if (body.Length > 0)
            {
                parameters += "body=" + body;
            }


            // String that will be converted into a signature.
            string canonicalString = API_KEY + http_date + parameters;


            //------------START HASH COMPUTATION---------------------
            // Compute the Base64 HMACSHA1 value
            HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

            // Compute the hash of the input file.
            byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

            String b64Mac         = hashValue.ToBase64String();
            String authentication = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);
            //-----------END HASH COMPUTATION------------------------


            string auth = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);


            System.Uri uri = new Uri(requestUrl);
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(uri.Host, uri.Port);
            string requestMethod = "POST " + uri.LocalPath + " HTTP/1.1\r\n";

            // Set Headers for the POST message
            requestHeaders += "Host: api.zeepmobile.com\r\n";
            requestHeaders += "Authorization: " + auth + "\r\n";
            requestHeaders += "Date: " + DateTime.UtcNow.ToString("r") + "\r\n";
            requestHeaders += "Content-Type: application/x-www-form-urlencoded\r\n";
            requestHeaders += "Content-Length: " + parameters.ToByteArray().Length + "\r\n";
            requestHeaders += "\r\n";


            // Get the data to be sent as a byte array.
            Byte[] data = System.Text.Encoding.UTF8.GetBytes(requestMethod + requestHeaders + parameters + "\r\n");
            // Send the message to the connected TcpServer.
            NetworkStream stream = client.GetStream();


            // SSL Authentication is used because the Server requires https.
            System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                stream,
                false,
                new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient(uri.Host);

            // Send the data over the SSL stream.
            sslStream.Write(data, 0, data.Length);
            sslStream.Flush();


            // Receive the TcpServer.response.
            for (int i = 0; i < 100; i++)
            {
                if (stream.DataAvailable)
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            Byte[] bytes = new byte[1024];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            while (stream.DataAvailable)
            {
                int count = sslStream.Read(bytes, 0, 1024);
                if (count == 0)
                {
                    break;
                }
                sb.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, count));
            }

            responseData = sb.ToString();
            Console.WriteLine(responseData);
            // Close everything.
            client.Close();

            return(responseData);
        }
Example #32
0
		public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
		{
			var encoding = Encoding.ASCII;

			var certificate = settings.Certificate;

			var certificates = new X509CertificateCollection();
			certificates.Add(certificate);


			var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

			var stream = new SslStream(client.GetStream(), true,
				(sender, cert, chain, sslErrs) => { return true; },
				(sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

			stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Tls, false);


			//Set up
			byte[] buffer = new byte[1482];
			int bufferIndex = 0;
			int bufferLevel = 0;
			int completePacketSize = 4 + 2 + 32;
			int recd = 0;
			DateTime minTimestamp = DateTime.Now.AddYears(-1);

			//Get the first feedback
			recd = stream.Read(buffer, 0, buffer.Length);

			//Continue while we have results and are not disposing
			while (recd > 0 && !cancelToken.IsCancellationRequested)
			{
				//Update how much data is in the buffer, and reset the position to the beginning
				bufferLevel += recd;
				bufferIndex = 0;

				try
				{
					//Process each complete notification "packet" available in the buffer
					while (bufferLevel - bufferIndex >= completePacketSize)
					{
						//Get our seconds since 1970 ?
						byte[] bSeconds = new byte[4];
						byte[] bDeviceToken = new byte[32];

						Array.Copy(buffer, bufferIndex, bSeconds, 0, 4);

						//Check endianness
						if (BitConverter.IsLittleEndian)
							Array.Reverse(bSeconds);

						int tSeconds = BitConverter.ToInt32(bSeconds, 0);

						//Add seconds since 1970 to that date, in UTC
						var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

						//flag to allow feedback times in UTC or local, but default is local
						if (!settings.FeedbackTimeIsUTC)
							timestamp = timestamp.ToLocalTime();

						//Now copy out the device token
						Array.Copy(buffer, bufferIndex + 6, bDeviceToken, 0, 32);

						var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

						//Make sure we have a good feedback tuple
						if (deviceToken.Length == 64
							&& timestamp > minTimestamp)
						{
							//Raise event
							try
							{
								RaiseFeedbackReceived(deviceToken, timestamp);
							}
							catch { }
						}

						//Keep track of where we are in the received data buffer
						bufferIndex += completePacketSize;
					}
				}
				catch { }

				//Figure out how much data we have left over in the buffer still
				bufferLevel -= bufferIndex;

				//Copy any leftover data in the buffer to the start of the buffer
				if (bufferLevel > 0)
					Array.Copy(buffer, bufferIndex, buffer, 0, bufferLevel);

				//Read the next feedback
				recd = stream.Read(buffer, bufferLevel, buffer.Length - bufferLevel);
			}

			try
			{
				stream.Close ();
				stream.Dispose();
			}
			catch { }

			try 
			{
				client.Client.Shutdown (SocketShutdown.Both);
				client.Client.Dispose ();
			}
			catch { }

			try { client.Close (); } catch { }

		}