Web API for the bulk printing desktop application.

Client.cs 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. using ExtensionMethods;
  2. using MAX.Models;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.IO;
  6. using System.Net.Sockets;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Xml;
  12. namespace MAX
  13. {
  14. public class Client : IDisposable
  15. {
  16. private ILogger logger;
  17. private string host;
  18. private int port;
  19. private int vendorId;
  20. private string serialNumber;
  21. private int userId;
  22. private string username;
  23. private string password;
  24. private TcpClient connection = null;
  25. private NetworkStream connectionStream = null;
  26. private TripleDES des = null;
  27. private bool disposed = false;
  28. public Client(ILogger logger, string host, int port, int vendorId, string serialNumber, int userId, string username, string password)
  29. {
  30. this.logger = logger;
  31. this.host = host;
  32. this.port = port;
  33. this.vendorId = vendorId;
  34. this.serialNumber = serialNumber;
  35. this.userId = userId;
  36. this.username = username;
  37. this.password = password;
  38. ConnectTimeout = 10000;
  39. ReceiveTimeout = 10000;
  40. SendTimeout = 10000;
  41. }
  42. public void Close()
  43. {
  44. Dispose(true);
  45. }
  46. public async Task<User> ConnectAsync()
  47. {
  48. if (connection != null)
  49. throw new Exception("Already connected");
  50. connection = new TcpClient(AddressFamily.InterNetwork);
  51. connection.ReceiveTimeout = ReceiveTimeout;
  52. connection.SendTimeout = SendTimeout;
  53. // Connect to the server
  54. try
  55. {
  56. using (var cancellationSource = new CancellationTokenSource(ConnectTimeout))
  57. {
  58. await connection.ConnectAsync(host, port).WithCancellation(cancellationSource.Token).ConfigureAwait(false);
  59. }
  60. }
  61. catch (OperationCanceledException)
  62. {
  63. throw new Exception("Connect timeout");
  64. }
  65. connectionStream = connection.GetStream();
  66. // Device authentication
  67. await WriteMessageAsync(new MessageBuilder()
  68. .Append("Hi ")
  69. .Append(serialNumber)
  70. .Append("|V")
  71. .Append(vendorId)
  72. .Append("|123451234512345||||||")).ConfigureAwait(false);
  73. var response = await ReadMessageAsync().ConfigureAwait(false);
  74. if (!response.StartsWith("Hi "))
  75. {
  76. logger.LogError("Device authentication failed: {0}", response);
  77. return null;
  78. }
  79. // Request server RSA key
  80. await WriteMessageAsync(new MessageBuilder().Append("PK")).ConfigureAwait(false);
  81. response = await ReadMessageAsync().ConfigureAwait(false);
  82. // Key exchange
  83. des = TripleDES.Create();
  84. des.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
  85. await WriteMessageAsync(new MessageBuilder()
  86. .Append("3D ")
  87. .Append(EncryptRSA(response, BitConverter.ToString(des.Key).Replace("-", "")))).ConfigureAwait(false);
  88. response = await ReadMessageAsync().ConfigureAwait(false);
  89. if (!response.StartsWith("OK"))
  90. {
  91. throw new Exception(String.Format("Key exchange failed: {0}", response));
  92. }
  93. // User authentication
  94. await WriteMessageAsync(new MessageBuilder()
  95. .Append("User ")
  96. .Append(Encrypt(new StringBuilder()
  97. .Append(userId)
  98. .Append("|")
  99. .Append(username)
  100. .Append("|")
  101. .Append(password).ToString()))).ConfigureAwait(false);
  102. response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  103. if (response.StartsWith("OK"))
  104. {
  105. var parts = response.Split('|');
  106. var user = new User()
  107. {
  108. Id = userId,
  109. Username = username,
  110. FirstName = parts[4],
  111. Surname = parts[3],
  112. Enabled = bool.Parse(parts[6]),
  113. Level = (User.UserLevel)int.Parse(parts[1]),
  114. System = int.Parse(parts[2]),
  115. LastLogin = DateTime.Parse(parts[5])
  116. };
  117. if (user.Level == User.UserLevel.CustomUser)
  118. {
  119. user.CanPrintOffline = bool.Parse(parts[7]);
  120. user.OfflinePrintValue = decimal.Parse(parts[8]);
  121. user.CanPrintOnline = bool.Parse(parts[9]);
  122. user.OnlinePrintValue = decimal.Parse(parts[10]);
  123. user.CanReprintOffline = bool.Parse(parts[11]);
  124. user.OfflineReprintValue = decimal.Parse(parts[12]);
  125. user.CanReprintOnline = bool.Parse(parts[13]);
  126. user.OnlineReprintValue = decimal.Parse(parts[14]);
  127. }
  128. // Account information
  129. await WriteMessageAsync(new MessageBuilder().Append("Acc")).ConfigureAwait(false);
  130. response = Decrypt(await ReadMessageAsync().ConfigureAwait(false));
  131. if (response.StartsWith("OK"))
  132. {
  133. parts = response.Split('|');
  134. user.Account = new Account()
  135. {
  136. Id = int.Parse(parts[1]),
  137. Name = parts[2],
  138. Balance = decimal.Parse(parts[3]),
  139. Status = (Account.AccountStatus)int.Parse(parts[4]),
  140. Reference = parts[5],
  141. Warehouse = new Warehouse()
  142. {
  143. Id = int.Parse(parts[6]),
  144. Name = parts[7]
  145. }
  146. };
  147. return user;
  148. }
  149. else if (response.StartsWith("ER"))
  150. {
  151. logger.LogError("Error retrieving account information: {0}", response);
  152. return null;
  153. }
  154. else
  155. {
  156. throw new Exception(String.Format("Invalid account information response: {0}", response));
  157. }
  158. }
  159. else if (response.StartsWith("ER"))
  160. {
  161. logger.LogInformation("User authentication failed: {0}", response);
  162. return null;
  163. }
  164. else
  165. {
  166. throw new Exception(String.Format("Invalid user information response: {0}", response));
  167. }
  168. }
  169. public int ConnectTimeout { get; set; }
  170. protected virtual void Dispose(bool disposing)
  171. {
  172. if (disposed)
  173. return;
  174. disposed = true;
  175. // No unmanaged resources are disposed so we don't need the full finalisation pattern.
  176. if (disposing)
  177. {
  178. if (des != null)
  179. {
  180. des.Dispose();
  181. des = null;
  182. }
  183. if (connectionStream != null)
  184. {
  185. connectionStream.Dispose();
  186. connectionStream = null;
  187. }
  188. if (connection != null)
  189. {
  190. connection.Dispose();
  191. connection = null;
  192. }
  193. }
  194. }
  195. public void Dispose()
  196. {
  197. Dispose(true);
  198. }
  199. private string Decrypt(string cipherText)
  200. {
  201. using (var decryptor = des.CreateDecryptor(des.Key, des.IV))
  202. {
  203. return Encoding.UTF8.GetString(Transform(decryptor, Convert.FromBase64String(cipherText)));
  204. }
  205. }
  206. private string Encrypt(string plainText)
  207. {
  208. using (var encryptor = des.CreateEncryptor(des.Key, des.IV))
  209. {
  210. return Convert.ToBase64String(Transform(encryptor, Encoding.UTF8.GetBytes(plainText)));
  211. }
  212. }
  213. private string EncryptRSA(string publicKey, string plainText)
  214. {
  215. RSAParameters parameters = new RSAParameters();
  216. var xml = new XmlDocument();
  217. xml.LoadXml(publicKey);
  218. if (! xml.DocumentElement.Name.Equals("RSAKeyValue"))
  219. throw new Exception("Invalid RSA key");
  220. foreach (XmlNode node in xml.DocumentElement.ChildNodes)
  221. {
  222. switch (node.Name)
  223. {
  224. case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break;
  225. case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break;
  226. case "P": parameters.P = Convert.FromBase64String(node.InnerText); break;
  227. case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break;
  228. case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break;
  229. case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break;
  230. case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break;
  231. case "D": parameters.D = Convert.FromBase64String(node.InnerText); break;
  232. }
  233. }
  234. using (var rsa = RSA.Create())
  235. {
  236. rsa.ImportParameters(parameters);
  237. var blockSize = rsa.KeySize / 8 - 42;
  238. var offset = 0;
  239. var input = Encoding.UTF32.GetBytes(plainText);
  240. StringBuilder output = new StringBuilder();
  241. while (offset < input.Length)
  242. {
  243. var length = input.Length - offset;
  244. if (length > blockSize)
  245. length = blockSize;
  246. var block = new byte[length];
  247. Array.Copy(input, offset, block, 0, length);
  248. var cipherText = rsa.Encrypt(block, RSAEncryptionPadding.OaepSHA1);
  249. Array.Reverse(cipherText);
  250. output.Append(Convert.ToBase64String(cipherText));
  251. offset += length;
  252. }
  253. return output.ToString();
  254. }
  255. }
  256. private async Task<byte[]> ReadBytesAsync(int count)
  257. {
  258. int totalBytesRead = 0;
  259. byte[] buffer = new byte[count];
  260. while (totalBytesRead < count)
  261. {
  262. int bytesRead = await connectionStream.ReadAsync(buffer, totalBytesRead, count - totalBytesRead).ConfigureAwait(false);
  263. if (bytesRead == 0)
  264. throw new Exception("Connection closed unexpectedly");
  265. totalBytesRead += bytesRead;
  266. }
  267. return buffer;
  268. }
  269. private async Task<string> ReadMessageAsync()
  270. {
  271. byte[] buffer = await ReadBytesAsync(2).ConfigureAwait(false);
  272. int size = buffer[0] * 256 + buffer[1];
  273. return Encoding.ASCII.GetString(await ReadBytesAsync(size).ConfigureAwait(false));
  274. }
  275. public int ReceiveTimeout { get; set; }
  276. public int SendTimeout { get; set; }
  277. private byte[] Transform(ICryptoTransform transform, byte[] input)
  278. {
  279. using (var memoryStream = new MemoryStream())
  280. using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
  281. {
  282. cryptoStream.Write(input, 0, input.Length);
  283. cryptoStream.FlushFinalBlock();
  284. return memoryStream.ToArray();
  285. }
  286. }
  287. private async Task WriteMessageAsync(MessageBuilder message)
  288. {
  289. byte[] data = message.GetBytes();
  290. await connectionStream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
  291. }
  292. }
  293. }