UrlUtils.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //
  2. // Permission is hereby granted, free of charge, to any person obtaining
  3. // a copy of this software and associated documentation files (the
  4. // "Software"), to deal in the Software without restriction, including
  5. // without limitation the rights to use, copy, modify, merge, publish,
  6. // distribute, sublicense, and/or sell copies of the Software, and to
  7. // permit persons to whom the Software is furnished to do so, subject to
  8. // the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be
  11. // included in all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  17. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  18. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. //
  21. /**
  22. * Namespace: System.Web.UI.Util
  23. * Class: UrlUtils
  24. *
  25. * Author: Gaurav Vaish
  26. * Maintainer: [email protected]
  27. * Status: ??%
  28. *
  29. * (C) Gaurav Vaish (2001)
  30. */
  31. using System;
  32. using System.Collections;
  33. using System.Text;
  34. using System.Web.SessionState;
  35. namespace System.Web.Util
  36. {
  37. internal class UrlUtils
  38. {
  39. /*
  40. * I could not find these functions in the class System.Uri
  41. * Besides, an instance of Uri will not be formed until and unless the address is of
  42. * the form protocol://[user:pass]host[:port]/[fullpath]
  43. * ie, a protocol, and that too without any blanks before,
  44. * is a must which may not be the case here.
  45. * Important: Escaped URL is assumed here. nothing like .aspx?path=/something
  46. * It should be .aspx?path=%2Fsomething
  47. */
  48. public static string GetProtocol(string url)
  49. {
  50. //Taking code from Java Class java.net.URL
  51. if(url!=null)
  52. {
  53. if(url.Length>0)
  54. {
  55. int i, start = 0, limit;
  56. limit = url.Length;
  57. char c;
  58. bool aRef = false;
  59. while( (limit > 0) && (url[limit-1] <= ' '))
  60. {
  61. limit --;
  62. }
  63. while( (start < limit) && (url[start] <= ' '))
  64. {
  65. start++;
  66. }
  67. if(RegionMatches(true, url, start, "url:", 0, 4))
  68. {
  69. start += 4;
  70. }
  71. if(start < url.Length && url[start]=='#')
  72. {
  73. aRef = true;
  74. }
  75. for(i = start; !aRef && (i < limit) && ((c=url[i]) != '/'); i++)
  76. {
  77. if(c==':')
  78. {
  79. return url.Substring(start, i - start);
  80. }
  81. }
  82. }
  83. }
  84. return String.Empty;
  85. }
  86. public static bool IsRelativeUrl(string url)
  87. {
  88. if (url.IndexOf(':') == -1)
  89. return !IsRooted(url);
  90. return false;
  91. }
  92. public static bool IsRootUrl(string url)
  93. {
  94. if(url!=null)
  95. {
  96. if(url.Length>0)
  97. {
  98. return IsValidProtocol(GetProtocol(url).ToLower());
  99. }
  100. }
  101. return true;
  102. }
  103. public static bool IsRooted(string path)
  104. {
  105. if(path!=null && path.Length > 0)
  106. {
  107. return (path[0]=='/' || path[0]=='\\');
  108. }
  109. return true;
  110. }
  111. public static void FailIfPhysicalPath(string path)
  112. {
  113. if(path!= null && path.Length > 1)
  114. {
  115. if(path[1]==':' || path.StartsWith(@"\\"))
  116. throw new HttpException(HttpRuntime.FormatResourceString("Physical_path_not_allowed", path));
  117. }
  118. }
  119. public static string Combine (string basePath, string relPath)
  120. {
  121. if (relPath == null)
  122. throw new ArgumentNullException ("relPath");
  123. int rlength = relPath.Length;
  124. if (rlength == 0)
  125. return "";
  126. FailIfPhysicalPath (relPath);
  127. relPath = relPath.Replace ("\\", "/");
  128. if (IsRooted (relPath))
  129. return Reduce (relPath);
  130. char first = relPath [0];
  131. if (rlength < 3 || first == '~' || first == '/' || first == '\\') {
  132. if (basePath == null || (basePath.Length == 1 && basePath [0] == '/'))
  133. basePath = String.Empty;
  134. string slash = (first == '/') ? "" : "/";
  135. if (first == '~') {
  136. if (rlength == 1) {
  137. relPath = "";
  138. } else if (rlength > 1 && relPath [1] == '/') {
  139. relPath = relPath.Substring (2);
  140. slash = "/";
  141. }
  142. string appvpath = HttpRuntime.AppDomainAppVirtualPath;
  143. if (appvpath.EndsWith ("/"))
  144. slash = "";
  145. return Reduce (appvpath + slash + relPath);
  146. }
  147. return Reduce (basePath + slash + relPath);
  148. }
  149. if (basePath == null || basePath == "")
  150. basePath = HttpRuntime.AppDomainAppVirtualPath;
  151. if (basePath.Length <= 1)
  152. basePath = String.Empty;
  153. return Reduce (basePath + "/" + relPath);
  154. }
  155. public static bool IsValidProtocol(string protocol)
  156. {
  157. if(protocol.Length < 1)
  158. return false;
  159. char c = protocol[0];
  160. if(!Char.IsLetter(c))
  161. {
  162. return false;
  163. }
  164. for(int i=1; i < protocol.Length; i++)
  165. {
  166. c = protocol[i];
  167. if(!Char.IsLetterOrDigit(c) && c!='.' && c!='+' && c!='-')
  168. {
  169. return false;
  170. }
  171. }
  172. return true;
  173. }
  174. /*
  175. * MakeRelative("http://www.foo.com/bar1/bar2/file","http://www.foo.com/bar1")
  176. * will return "bar2/file"
  177. * while MakeRelative("http://www.foo.com/bar1/...","http://www.anotherfoo.com")
  178. * return 'null' and so does the call
  179. * MakeRelative("http://www.foo.com/bar1/bar2","http://www.foo.com/bar")
  180. */
  181. public static string MakeRelative(string fullUrl, string relativeTo)
  182. {
  183. if (fullUrl == relativeTo)
  184. return String.Empty;
  185. if (fullUrl.IndexOf (relativeTo) != 0)
  186. return null;
  187. string leftOver = fullUrl.Substring (relativeTo.Length);
  188. if (leftOver.Length > 0 && leftOver [0] == '/')
  189. leftOver = leftOver.Substring (1);
  190. leftOver = Reduce (leftOver);
  191. if (leftOver.Length > 0 && leftOver [0] == '/')
  192. leftOver = leftOver.Substring (1);
  193. return leftOver;
  194. }
  195. /*
  196. * Check JavaDocs for java.lang.String#RegionMatches(bool, int, String, int, int)
  197. * Could not find anything similar in the System.String class
  198. */
  199. public static bool RegionMatches(bool ignoreCase, string source, int start, string match, int offset, int len)
  200. {
  201. if(source!=null || match!=null)
  202. {
  203. if(source.Length>0 && match.Length>0)
  204. {
  205. char[] ta = source.ToCharArray();
  206. char[] pa = match.ToCharArray();
  207. if((offset < 0) || (start < 0) || (start > (source.Length - len)) || (offset > (match.Length - len)))
  208. {
  209. return false;
  210. }
  211. while(len-- > 0)
  212. {
  213. char c1 = ta[start++];
  214. char c2 = pa[offset++];
  215. if(c1==c2)
  216. continue;
  217. if(ignoreCase)
  218. {
  219. if(Char.ToUpper(c1)==Char.ToUpper(c2))
  220. continue;
  221. // Check for Gregorian Calendar where the above may not hold good
  222. if(Char.ToLower(c1)==Char.ToLower(c2))
  223. continue;
  224. }
  225. return false;
  226. }
  227. return true;
  228. }
  229. }
  230. return false;
  231. }
  232. public static string Reduce (string path)
  233. {
  234. path = path.Replace ('\\','/');
  235. string [] parts = path.Split ('/');
  236. ArrayList result = new ArrayList ();
  237. int end = parts.Length;
  238. for (int i = 0; i < end; i++) {
  239. string current = parts [i];
  240. if (current == "." )
  241. continue;
  242. if (current == "..") {
  243. if (result.Count == 0) {
  244. if (i == 1) // see bug 52599
  245. continue;
  246. throw new HttpException ("Invalid path.");
  247. }
  248. result.RemoveAt (result.Count - 1);
  249. continue;
  250. }
  251. result.Add (current);
  252. }
  253. if (result.Count == 0)
  254. return "/";
  255. return String.Join ("/", (string []) result.ToArray (typeof (string)));
  256. }
  257. public static string GetDirectory(string url)
  258. {
  259. if(url==null)
  260. {
  261. return null;
  262. }
  263. if(url.Length==0)
  264. {
  265. return String.Empty;
  266. }
  267. url = url.Replace('\\','/');
  268. string baseDir = "";
  269. int last = url.LastIndexOf ('/');
  270. if (last > 0)
  271. baseDir = url.Substring(0, url.LastIndexOf('/'));
  272. if(baseDir.Length==0)
  273. {
  274. baseDir = "/";
  275. }
  276. return baseDir;
  277. }
  278. static string GetFile (string url)
  279. {
  280. if (url == null)
  281. return null;
  282. if (url.Length == 0)
  283. return String.Empty;
  284. url = url.Replace ('\\', '/');
  285. int last = url.LastIndexOf ('/') + 1;
  286. if (last != 0) {
  287. url = url.Substring (last);
  288. }
  289. return url;
  290. }
  291. public static string InsertSessionId (string id, string path)
  292. {
  293. string dir = GetDirectory (path);
  294. if (!dir.EndsWith ("/"))
  295. dir += "/";
  296. return Reduce (dir + "(" + id + ")/" + GetFile (path));
  297. }
  298. public static string GetSessionId (string path)
  299. {
  300. int len = path.Length;
  301. if ((len < SessionId.IdLength + 2) || (path [len - 1] != ')') ||
  302. (path [len - SessionId.IdLength - 2] != '('))
  303. return null;
  304. return path.Substring (len - SessionId.IdLength - 1, SessionId.IdLength);
  305. }
  306. public static string RemoveSessionId (string base_path, string file_path)
  307. {
  308. int len = base_path.Length;
  309. string dir = base_path.Substring (0, len - SessionId.IdLength - 2);
  310. if (!dir.EndsWith ("/"))
  311. dir += "/";
  312. return Reduce (dir + GetFile (file_path));
  313. }
  314. public static string ResolveVirtualPathFromAppAbsolute (string path)
  315. {
  316. if (path [0] != '~') return path;
  317. if (path.Length == 1)
  318. return HttpRuntime.AppDomainAppVirtualPath;
  319. if (path [1] == '/' || path [1] == '\\') {
  320. string appPath = HttpRuntime.AppDomainAppVirtualPath;
  321. if (appPath.Length > 1)
  322. return appPath + "/" + path.Substring (2);
  323. return "/" + path.Substring (2);
  324. }
  325. return path;
  326. }
  327. public static string ResolvePhysicalPathFromAppAbsolute (string path)
  328. {
  329. if (path [0] != '~') return path;
  330. if (path.Length == 1)
  331. return HttpRuntime.AppDomainAppPath;
  332. if (path [1] == '/' || path [1] == '\\') {
  333. string appPath = HttpRuntime.AppDomainAppPath;
  334. if (appPath.Length > 1)
  335. return appPath + "/" + path.Substring (2);
  336. return "/" + path.Substring (2);
  337. }
  338. return path;
  339. }
  340. }
  341. }