123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320 |
- /*
- Copyright (c) 2013, 2014 Paolo Patierno
- All rights reserved. This program and the accompanying materials
- are made available under the terms of the Eclipse Public License v1.0
- and Eclipse Distribution License v1.0 which accompany this distribution.
- The Eclipse Public License is available at
- http://www.eclipse.org/legal/epl-v10.html
- and the Eclipse Distribution License is available at
- http://www.eclipse.org/org/documents/edl-v10.php.
- Contributors:
- Paolo Patierno - initial API and implementation and/or initial documentation
- */
- #if SSL
- #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
- using Microsoft.SPOT.Net.Security;
- #else
- using System.Net.Security;
- using System.Security.Authentication;
- #endif
- #endif
- using System.Net.Sockets;
- using System.Net;
- using System.Security.Cryptography.X509Certificates;
- using System;
- namespace uPLibrary.Networking.M2Mqtt
- {
- /// <summary>
- /// Channel to communicate over the network
- /// </summary>
- public class MqttNetworkChannel : IMqttNetworkChannel
- {
- #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
- private readonly RemoteCertificateValidationCallback userCertificateValidationCallback;
- private readonly LocalCertificateSelectionCallback userCertificateSelectionCallback;
- #endif
- // remote host information
- private string remoteHostName;
- private IPAddress remoteIpAddress;
- private int remotePort;
- // socket for communication
- private Socket socket;
- // using SSL
- private bool secure;
- // CA certificate
- private X509Certificate caCert;
- /// <summary>
- /// Remote host name
- /// </summary>
- public string RemoteHostName { get { return this.remoteHostName; } }
- /// <summary>
- /// Remote IP address
- /// </summary>
- public IPAddress RemoteIpAddress { get { return this.remoteIpAddress; } }
- /// <summary>
- /// Remote port
- /// </summary>
- public int RemotePort { get { return this.remotePort; } }
- #if SSL
- // SSL stream
- private SslStream sslStream;
- #if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
- private NetworkStream netStream;
- #endif
- #endif
- /// <summary>
- /// Data available on the channel
- /// </summary>
- public bool DataAvailable
- {
- get
- {
- #if SSL
- #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
- if (secure)
- return this.sslStream.DataAvailable;
- else
- return (this.socket.Available > 0);
- #else
- if (secure)
- return this.netStream.DataAvailable;
- else
- return (this.socket.Available > 0);
- #endif
- #else
- return (this.socket.Available > 0);
- #endif
- }
- }
- /// <summary>
- /// Constructor
- /// </summary>
- /// <param name="socket">Socket opened with the client</param>
- public MqttNetworkChannel(Socket socket)
- {
- this.socket = socket;
- }
- /// <summary>
- /// Constructor
- /// </summary>
- /// <param name="remoteHostName">Remote Host name</param>
- /// <param name="remotePort">Remote port</param>
- public MqttNetworkChannel(string remoteHostName, int remotePort)
- #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
- : this(remoteHostName, remotePort, false, null, null, null)
- #else
- : this(remoteHostName, remotePort, false, null)
- #endif
- {
- }
- /// <summary>
- /// Constructor
- /// </summary>
- /// <param name="remoteHostName">Remote Host name</param>
- /// <param name="remotePort">Remote port</param>
- /// <param name="secure">Using SSL</param>
- /// <param name="caCert">CA certificate</param>
- #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
- /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
- /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
- public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert,
- RemoteCertificateValidationCallback userCertificateValidationCallback,
- LocalCertificateSelectionCallback userCertificateSelectionCallback)
- #else
- public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert)
- #endif
- {
- IPAddress remoteIpAddress = null;
- try
- {
- // check if remoteHostName is a valid IP address and get it
- remoteIpAddress = IPAddress.Parse(remoteHostName);
- }
- catch
- {
- }
- // in this case the parameter remoteHostName isn't a valid IP address
- if (remoteIpAddress == null)
- {
- IPHostEntry hostEntry = Dns.GetHostEntry(remoteHostName);
- if ((hostEntry != null) && (hostEntry.AddressList.Length > 0))
- {
- // check for the first address not null
- // it seems that with .Net Micro Framework, the IPV6 addresses aren't supported and return "null"
- int i = 0;
- while (hostEntry.AddressList[i] == null) i++;
- remoteIpAddress = hostEntry.AddressList[i];
- }
- else
- {
- throw new Exception("No address found for the remote host name");
- }
- }
- this.remoteHostName = remoteHostName;
- this.remoteIpAddress = remoteIpAddress;
- this.remotePort = remotePort;
- this.secure = secure;
- this.caCert = caCert;
- #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
- this.userCertificateValidationCallback = userCertificateValidationCallback;
- this.userCertificateSelectionCallback = userCertificateSelectionCallback;
- #endif
- }
- /// <summary>
- /// Connect to remote server
- /// </summary>
- public void Connect()
- {
- this.socket = new Socket(this.remoteIpAddress.GetAddressFamily(), SocketType.Stream, ProtocolType.Tcp);
- // try connection to the broker
- this.socket.Connect(new IPEndPoint(this.remoteIpAddress, this.remotePort));
- #if SSL
- // secure channel requested
- if (secure)
- {
- // create SSL stream
- #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
- this.sslStream = new SslStream(this.socket);
- #else
- this.netStream = new NetworkStream(this.socket);
- this.sslStream = new SslStream(this.netStream, false, this.userCertificateValidationCallback, this.userCertificateSelectionCallback);
- #endif
- // server authentication (SSL/TLS handshake)
- #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
- this.sslStream.AuthenticateAsClient(this.remoteHostName,
- null,
- new X509Certificate[] { this.caCert },
- SslVerification.CertificateRequired,
- SslProtocols.TLSv1);
- #else
- this.sslStream.AuthenticateAsClient(
- this.remoteHostName,
- null,
- SslProtocols.Tls,
- false);
-
- #endif
- }
- #endif
- }
- /// <summary>
- /// Send data on the network channel
- /// </summary>
- /// <param name="buffer">Data buffer to send</param>
- /// <returns>Number of byte sent</returns>
- public int Send(byte[] buffer)
- {
- #if SSL
- if (this.secure)
- {
- this.sslStream.Write(buffer, 0, buffer.Length);
- return buffer.Length;
- }
- else
- return this.socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
- #else
- return this.socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
- #endif
- }
- /// <summary>
- /// Receive data from the network
- /// </summary>
- /// <param name="buffer">Data buffer for receiving data</param>
- /// <returns>Number of bytes received</returns>
- public int Receive(byte[] buffer)
- {
- #if SSL
- if (this.secure)
- {
- // read all data needed (until fill buffer)
- int idx = 0;
- while (idx < buffer.Length)
- {
- idx += this.sslStream.Read(buffer, idx, buffer.Length - idx);
- }
- return buffer.Length;
- }
- else
- {
- // read all data needed (until fill buffer)
- int idx = 0;
- while (idx < buffer.Length)
- {
- idx += this.socket.Receive(buffer, idx, buffer.Length - idx, SocketFlags.None);
- }
- return buffer.Length;
- }
- #else
- // read all data needed (until fill buffer)
- int idx = 0;
- while (idx < buffer.Length)
- {
- idx += this.socket.Receive(buffer, idx, buffer.Length - idx, SocketFlags.None);
- }
- return buffer.Length;
- #endif
- }
- /// <summary>
- /// Close the network channel
- /// </summary>
- public void Close()
- {
- #if SSL
- if (this.secure)
- {
- #if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
- this.netStream.Close();
- #endif
- this.sslStream.Close();
- }
- this.socket.Close();
- #else
- this.socket.Close();
- #endif
- }
- }
- /// <summary>
- /// IPAddress Utility class
- /// </summary>
- public static class IPAddressUtility
- {
- /// <summary>
- /// Return AddressFamily for the IP address
- /// </summary>
- /// <param name="ipAddress">IP address to check</param>
- /// <returns>Address family</returns>
- public static AddressFamily GetAddressFamily(this IPAddress ipAddress)
- {
- #if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
- return ipAddress.AddressFamily;
- #else
- return (ipAddress.ToString().IndexOf(':') != -1) ?
- AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
- #endif
- }
- }
- }
|