PageRenderTime 26ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/FileFind.Meshwork/FileFind/Common.cs

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