PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Meshwork.Common/Utils.cs

https://github.com/codebutler/meshwork
C# | 338 lines | 253 code | 39 blank | 46 comment | 44 complexity | 54072a7726ffc9ffd4926a87d5a63379 MD5 | raw file
Possible License(s): GPL-3.0
  1. //
  2. // Utils.cs:
  3. //
  4. // Authors:
  5. // Eric Butler <eric@extremeboredom.net>
  6. //
  7. // (C) 2006 FileFind.net (http://filefind.net)
  8. //
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Net.Sockets;
  15. using System.Security.Cryptography;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. namespace Meshwork.Common
  19. {
  20. public static class Utils
  21. {
  22. public static bool IsValidEmail (string inputEmail)
  23. {
  24. var strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
  25. @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
  26. @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
  27. var re = new Regex (strRegex);
  28. if (re.IsMatch (inputEmail))
  29. return (true);
  30. return (false);
  31. }
  32. public static ulong GetUnixTimestamp()
  33. {
  34. var t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
  35. return (ulong)t.TotalSeconds;
  36. }
  37. public static DateTime ParseUnixTimestamp (ulong time)
  38. {
  39. var epoch = new DateTime(1970, 1, 1);
  40. return epoch.AddSeconds(time);
  41. }
  42. public static bool IsNumeric(string N) {
  43. try {
  44. long.Parse(N);
  45. } catch (Exception) {
  46. return false;
  47. }
  48. return true;
  49. }
  50. public static bool SupportsIPv6 {
  51. get {
  52. // XXX: This doesnt work? return Socket.OSSupportsIPv6;
  53. try {
  54. var tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  55. tmp.Close();
  56. return true;
  57. }
  58. catch {
  59. return false;
  60. }
  61. }
  62. }
  63. public static string BytesToString(byte[] b) {
  64. string tmpstr = null;
  65. if (!(b == null)) {
  66. for (var x = 0; x <= b.Length - 1; x++) {
  67. tmpstr += b[x].ToString("X2");
  68. }
  69. }
  70. return tmpstr;
  71. }
  72. public static byte[] StringToBytes(string str)
  73. {
  74. if ((str.Length % 2) != 0) {
  75. throw new ArgumentException("Str has bad length");
  76. }
  77. var result = new byte[str.Length / 2];
  78. for (var x = 0; x < str.Length; x += 2) {
  79. result[x/2] = byte.Parse(str.Substring(x, 2), NumberStyles.HexNumber);
  80. }
  81. return result;
  82. }
  83. public static string MD5(byte[] bytesIn) {
  84. var bytesOut = new MD5CryptoServiceProvider().ComputeHash(bytesIn);
  85. var stringOut = BitConverter.ToString(bytesOut).Replace("-", string.Empty);
  86. return stringOut.ToLower ();
  87. }
  88. public static string MD5(string stringIn) {
  89. var bytesIn = Encoding.UTF8.GetBytes(stringIn);
  90. var bytesOut = new MD5CryptoServiceProvider().ComputeHash(bytesIn);
  91. var stringOut = BitConverter.ToString(bytesOut).Replace("-", string.Empty);
  92. return stringOut.ToLower ();
  93. }
  94. public static string SHA(byte[] bytesIn) {
  95. var SHAObj = SHA1.Create();
  96. var bytesOut = SHAObj.ComputeHash(bytesIn);
  97. var strOut = BitConverter.ToString(bytesOut).Replace("-","");
  98. return strOut.ToLower ();
  99. }
  100. public static byte[] SHA512 (string stringIn)
  101. {
  102. SHA512 shaManaged = new SHA512Managed ();
  103. return shaManaged.ComputeHash (Encoding.ASCII.GetBytes (stringIn));
  104. }
  105. public static string SHA512Str (string stringIn)
  106. {
  107. return BitConverter.ToString(SHA512(stringIn)).Replace("-","");
  108. }
  109. public static string SHA512Str (byte[] bytesIn)
  110. {
  111. SHA512 shaManaged = new SHA512Managed();
  112. return BitConverter.ToString(shaManaged.ComputeHash(bytesIn));
  113. }
  114. public static string AddLineBreaks(string strIn)
  115. {
  116. var strOut = "";
  117. while (strIn != "") {
  118. if (strIn.Length >= 65) {
  119. strOut += strIn.Substring(0, 65) + Environment.NewLine;
  120. strIn = strIn.Substring(65);
  121. } else {
  122. strOut += strIn;
  123. strIn = "";
  124. }
  125. }
  126. return strOut;
  127. }
  128. public static bool IsInternalIP (IPAddress address)
  129. {
  130. if (address.AddressFamily == AddressFamily.InterNetwork) {
  131. var bytes = address.GetAddressBytes();
  132. return (bytes[0] == 10) || (bytes[0] == 192 && bytes[1] == 168) ||
  133. (bytes[0] == 172 && (bytes[1] >= 16 && bytes[1] <= 31)) ||
  134. (bytes[0] == 169 && bytes[1] == 254);
  135. }
  136. if (address.AddressFamily == AddressFamily.InterNetworkV6) {
  137. return address.IsIPv6LinkLocal;
  138. }
  139. throw new ArgumentException("address must be IPv4 or IPv6");
  140. }
  141. public static string FormatFingerprint (string fingerprint)
  142. {
  143. return fingerprint.CutIntoSetsOf(8).Join(" ");
  144. }
  145. public static string FormatFingerprint (string fingerprint, int sectionsPerLine)
  146. {
  147. return fingerprint.CutIntoSetsOf(8).EnumSlice(sectionsPerLine).Select(x => x.Join(" ")).Join("\n");
  148. }
  149. public static string FormatBytes (decimal bytes)
  150. {
  151. if (bytes >= 1099511627776)
  152. return Math.Round((bytes / 1024 / 1024 / 1024 / 1024),2) + " TB";
  153. if (bytes >= 1073741824)
  154. return Math.Round((bytes / 1024 / 1024 / 1024),2) + " GB";
  155. if (bytes >= 1048576)
  156. return Math.Round((bytes / 1024 / 1024),2) + " MB";
  157. if (bytes >= 1024)
  158. return Math.Round((bytes / 1024),2) + " KB";
  159. if (bytes < 1024)
  160. return bytes + " Bytes";
  161. return "0 Bytes";
  162. }
  163. public static string FormatNumber (long number)
  164. {
  165. var nfi = new CultureInfo( "en-US", false ).NumberFormat;
  166. nfi.NumberDecimalDigits = 0;
  167. return number.ToString("N",nfi);
  168. }
  169. public static bool WildcardMatch (string text, string pattern)
  170. {
  171. return Regex.Match(text, ToRegexPattern(pattern)).Success;
  172. }
  173. /* From the mono class library source */
  174. /* /mcs/class/System.Web/System.Web.Configuration/HandlerItem.cs */
  175. private static string ToRegexPattern (string dosPattern)
  176. {
  177. var result = dosPattern.Replace (".", "\\.");
  178. result = result.Replace ("*", ".*");
  179. result = result.Replace ('?', '.');
  180. return result;
  181. }
  182. public static bool IsValidIP (string ip)
  183. {
  184. /* XXX: Perhaps use these beautiful regexes I found...
  185. // IPv4
  186. if (Regex.IsMatch (address, @"(\d{1,3}\.){3}\d{1,3}") == true) {
  187. return true;
  188. // IPv6
  189. } else if (Regex.IsMatch (address, @"^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$") == true) {
  190. return true;
  191. } else {
  192. return false;
  193. }
  194. */
  195. try {
  196. IPAddress.Parse(ip);
  197. return true;
  198. } catch (Exception) {
  199. return false;
  200. }
  201. }
  202. /* private static Regex GetRegex (string verb) {
  203. // EnsureCache ();
  204. // if (regexCache.ContainsKey (verb))
  205. // return (Regex) regexCache [verb];
  206. StringBuilder result = new StringBuilder ("\\A");
  207. string [] expressions = verb.Split (',');
  208. int end = expressions.Length;
  209. for (int i = 0; i < end; i++) {
  210. string regex = ToRegexPattern (expressions [i]);
  211. if (i + 1 < end) {
  212. result.AppendFormat ("{0}\\z|\\A", regex);
  213. } else {
  214. result.AppendFormat ("({0})\\z", regex);
  215. }
  216. }
  217. Regex r = new Regex (result.ToString ());
  218. // regexCache [verb] = r;
  219. return r;
  220. }*/
  221. public static bool ParseSizeString(string str, out ulong num, out string unitName)
  222. {
  223. str = Regex.Replace(str, @"\s+", "");
  224. unitName = null;
  225. num = 0;
  226. var suffixes = new Dictionary<string,string>();
  227. suffixes.Add("b", "bit");
  228. suffixes.Add("B", "byte");
  229. suffixes.Add("Kb", "kilobit");
  230. suffixes.Add("KB", "kilobyte");
  231. suffixes.Add("Mb", "megabit");
  232. suffixes.Add("MB", "megabyte");
  233. suffixes.Add("Gb", "gigabit");
  234. suffixes.Add("GB", "gigabyte");
  235. // These are a bit ambiguous but commonly used...
  236. suffixes.Add("mb", "megabyte");
  237. suffixes.Add("m", "megabyte");
  238. suffixes.Add("M", "megabyte");
  239. suffixes.Add("k", "kilobyte");
  240. suffixes.Add("K", "kilobyte");
  241. suffixes.Add("kb", "kilobyte");
  242. suffixes.Add("gb", "gigabyte");
  243. suffixes.Add("G", "gigabyte");
  244. suffixes.Add("g", "gigabyte");
  245. // Check that the string has numbers followed by letters,
  246. // for example "10MB".
  247. var match = Regex.Match(str, @"^(\d+)([A-Za-z]+)$");
  248. if (match.Success) {
  249. if (ulong.TryParse(match.Groups[1].Captures[0].Value.Trim(), out num)) {
  250. unitName = match.Groups[2].Captures[0].Value.Trim();
  251. }
  252. } else {
  253. // If all numeric, default to megabytes
  254. match = Regex.Match(str, @"^(\d+)$");
  255. if (match.Success) {
  256. if (ulong.TryParse(match.Groups[1].Captures[0].Value, out num)) {
  257. unitName = "mb";
  258. }
  259. }
  260. if (unitName == null) {
  261. unitName = "shait";
  262. }
  263. }
  264. if (unitName != null && suffixes.ContainsKey(unitName)) {
  265. unitName = suffixes[unitName];
  266. return true;
  267. }
  268. unitName = null;
  269. return false;
  270. }
  271. public static bool ValidateSizeStr (string str)
  272. {
  273. ulong num;
  274. string unitName;
  275. return (ParseSizeString(str, out num, out unitName));
  276. }
  277. public static ulong SizeStringToBytes (string str)
  278. {
  279. ulong num;
  280. string unitName;
  281. if (ParseSizeString(str, out num, out unitName)) {
  282. switch (unitName) {
  283. case "byte":
  284. return num;
  285. case "kilobyte":
  286. return num * 1024;
  287. case "megabyte":
  288. return num * 1048576;
  289. case "gigabyte":
  290. return num * 1073741824;
  291. default:
  292. return 0;
  293. }
  294. }
  295. return 0;
  296. }
  297. }
  298. }