HttpRequest.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  1. //
  2. // System.Web.HttpRequest.cs
  3. //
  4. //
  5. // Author:
  6. // Miguel de Icaza ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Marek Habersack <[email protected]>
  9. //
  10. //
  11. // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
  12. // Copyright (C) 2011-2012 Xamarin, Inc (http://xamarin.com)
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System.Text;
  34. using System.Collections;
  35. using System.Collections.Specialized;
  36. using System.IO;
  37. using System.Runtime.InteropServices;
  38. using System.Security;
  39. using System.Security.Permissions;
  40. using System.Security.Principal;
  41. using System.Web.Configuration;
  42. using System.Web.Management;
  43. using System.Web.UI;
  44. using System.Web.Util;
  45. using System.Globalization;
  46. #if NET_4_0
  47. using System.Security.Authentication.ExtendedProtection;
  48. using System.Web.Routing;
  49. #endif
  50. namespace System.Web
  51. {
  52. // CAS - no InheritanceDemand here as the class is sealed
  53. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  54. public sealed partial class HttpRequest
  55. {
  56. HttpWorkerRequest worker_request;
  57. HttpContext context;
  58. WebROCollection query_string_nvc;
  59. //
  60. //string filename;
  61. string orig_url = null;
  62. UriBuilder url_components;
  63. string client_target;
  64. //
  65. // On-demand computed values
  66. //
  67. HttpBrowserCapabilities browser_capabilities;
  68. string file_path, base_virtual_dir, root_virtual_dir, client_file_path;
  69. string content_type;
  70. int content_length = -1;
  71. Encoding encoding;
  72. string current_exe_path;
  73. string physical_path;
  74. string unescaped_path;
  75. string original_path;
  76. string path_info;
  77. string raw_url;
  78. WebROCollection all_params;
  79. WebROCollection headers;
  80. Stream input_stream;
  81. InputFilterStream input_filter;
  82. Stream filter;
  83. HttpCookieCollection cookies;
  84. string http_method;
  85. WebROCollection form;
  86. HttpFileCollection files;
  87. ServerVariablesCollection server_variables;
  88. HttpClientCertificate client_cert;
  89. string request_type;
  90. string [] accept_types;
  91. string [] user_languages;
  92. Uri cached_url;
  93. TempFileStream request_file;
  94. readonly static System.Net.IPAddress [] host_addresses;
  95. // Validations
  96. bool validate_cookies, validate_query_string, validate_form;
  97. bool checked_cookies, checked_query_string, checked_form;
  98. static readonly UrlMappingCollection urlMappings;
  99. readonly static char [] queryTrimChars = {'?'};
  100. #if NET_4_0
  101. bool lazyFormValidation;
  102. bool lazyQueryStringValidation;
  103. bool inputValidationEnabled;
  104. RequestContext requestContext;
  105. BufferlessInputStream bufferlessInputStream;
  106. static bool validateRequestNewMode;
  107. internal static bool ValidateRequestNewMode {
  108. get { return validateRequestNewMode; }
  109. }
  110. internal bool InputValidationEnabled {
  111. get { return inputValidationEnabled; }
  112. }
  113. private static char[] RequestPathInvalidCharacters {
  114. get; set;
  115. }
  116. private static char[] CharsFromList (string list)
  117. {
  118. // List format is very strict and enforced by the Configuration
  119. // there must be a single char separated by commas with no trailing comma
  120. // whitespace is allowed though and should be trimmed.
  121. string [] pieces = list.Split (',');
  122. char [] chars = new char [pieces.Length];
  123. for (int i = 0; i < chars.Length; i++) {
  124. string trimmed = pieces [i].Trim ();
  125. if (trimmed.Length != 1) {
  126. // This should have been caught by System.Web.Configuration
  127. // and throw a configuration error. This is just here for sanity
  128. throw new System.Configuration.ConfigurationErrorsException ();
  129. }
  130. chars [i] = trimmed [0];
  131. }
  132. return chars;
  133. }
  134. #endif
  135. static HttpRequest ()
  136. {
  137. try {
  138. UrlMappingsSection ums = WebConfigurationManager.GetWebApplicationSection ("system.web/urlMappings") as UrlMappingsSection;
  139. if (ums != null && ums.IsEnabled) {
  140. urlMappings = ums.UrlMappings;
  141. if (urlMappings.Count == 0)
  142. urlMappings = null;
  143. }
  144. #if NET_4_0
  145. Version validationMode = HttpRuntime.Section.RequestValidationMode;
  146. if (validationMode >= new Version (4, 0)) {
  147. validateRequestNewMode = true;
  148. string invalidChars = HttpRuntime.Section.RequestPathInvalidCharacters;
  149. if (!String.IsNullOrEmpty (invalidChars))
  150. RequestPathInvalidCharacters = CharsFromList (invalidChars);
  151. }
  152. #endif
  153. } catch {
  154. // unlikely to happen
  155. }
  156. host_addresses = GetLocalHostAddresses ();
  157. }
  158. public HttpRequest (string filename, string url, string queryString)
  159. {
  160. // warning 169: what are we supposed to do with filename?
  161. //this.filename = filename;
  162. orig_url = url;
  163. url_components = new UriBuilder (url);
  164. url_components.Query = queryString;
  165. query_string_nvc = new WebROCollection ();
  166. if (queryString != null)
  167. HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
  168. query_string_nvc.Protect ();
  169. }
  170. internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
  171. {
  172. this.worker_request = worker_request;
  173. this.context = context;
  174. }
  175. internal UriBuilder UrlComponents {
  176. get {
  177. if (url_components == null) {
  178. string query;
  179. byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
  180. if(queryStringRaw != null)
  181. query = ContentEncoding.GetString(queryStringRaw);
  182. else
  183. query = worker_request.GetQueryString();
  184. BuildUrlComponents (ApplyUrlMapping (worker_request.GetUriPath ()), query);
  185. }
  186. return url_components;
  187. }
  188. }
  189. void BuildUrlComponents (string path, string query)
  190. {
  191. if (url_components != null)
  192. return;
  193. url_components = new UriBuilder ();
  194. url_components.Scheme = worker_request.GetProtocol ();
  195. url_components.Host = worker_request.GetServerName ();
  196. url_components.Port = worker_request.GetLocalPort ();
  197. url_components.Path = path;
  198. if (query != null && query.Length > 0)
  199. url_components.Query = query.TrimStart (queryTrimChars);
  200. }
  201. internal string ApplyUrlMapping (string url)
  202. {
  203. if (urlMappings == null)
  204. return url;
  205. string relUrl = VirtualPathUtility.ToAppRelative (url);
  206. UrlMapping um = null;
  207. foreach (UrlMapping u in urlMappings) {
  208. if (u == null)
  209. continue;
  210. if (String.Compare (relUrl, u.Url, StringComparison.Ordinal) == 0) {
  211. um = u;
  212. break;
  213. }
  214. }
  215. if (um == null)
  216. return url;
  217. string rawUrl = VirtualPathUtility.ToAbsolute (um.MappedUrl.Trim ());
  218. Uri newUrl = new Uri ("http://host.com" + rawUrl);
  219. if (url_components != null) {
  220. url_components.Path = newUrl.AbsolutePath;
  221. url_components.Query = newUrl.Query.TrimStart (queryTrimChars);
  222. query_string_nvc = new WebROCollection ();
  223. HttpUtility.ParseQueryString (newUrl.Query, Encoding.Default, query_string_nvc);
  224. query_string_nvc.Protect ();
  225. } else
  226. BuildUrlComponents (newUrl.AbsolutePath, newUrl.Query);
  227. return url_components.Path;
  228. }
  229. string [] SplitHeader (int header_index)
  230. {
  231. string [] result = null;
  232. string header = worker_request.GetKnownRequestHeader (header_index);
  233. if (header != null && header != "" && header.Trim () != "") {
  234. result = header.Split (',');
  235. for (int i = result.Length - 1; i >= 0; i--)
  236. result [i] = result [i].Trim ();
  237. }
  238. return result;
  239. }
  240. public string [] AcceptTypes {
  241. get {
  242. if (worker_request == null)
  243. return null;
  244. if (accept_types == null)
  245. accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
  246. return accept_types;
  247. }
  248. }
  249. #if !TARGET_JVM
  250. public WindowsIdentity LogonUserIdentity {
  251. get { throw new NotImplementedException (); }
  252. }
  253. #endif
  254. string anonymous_id;
  255. public string AnonymousID {
  256. get {
  257. return anonymous_id;
  258. }
  259. internal set {
  260. anonymous_id = value;
  261. }
  262. }
  263. public string ApplicationPath {
  264. get {
  265. if (worker_request == null)
  266. return null;
  267. return worker_request.GetAppPath ();
  268. }
  269. }
  270. public HttpBrowserCapabilities Browser {
  271. get {
  272. if (browser_capabilities == null)
  273. #if NET_4_0
  274. browser_capabilities = HttpCapabilitiesBase.BrowserCapabilitiesProvider.GetBrowserCapabilities (this);
  275. #else
  276. browser_capabilities = (HttpBrowserCapabilities)
  277. HttpCapabilitiesBase.GetConfigCapabilities (null, this);
  278. #endif
  279. return browser_capabilities;
  280. }
  281. set {
  282. browser_capabilities = value;
  283. }
  284. }
  285. internal bool BrowserMightHaveSpecialWriter {
  286. get {
  287. return (browser_capabilities != null
  288. || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
  289. }
  290. }
  291. internal bool BrowserMightHaveAdapters {
  292. get {
  293. return (browser_capabilities != null
  294. || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
  295. }
  296. }
  297. public HttpClientCertificate ClientCertificate {
  298. get {
  299. if (client_cert == null)
  300. client_cert = new HttpClientCertificate (worker_request);
  301. return client_cert;
  302. }
  303. }
  304. static internal string GetParameter (string header, string attr)
  305. {
  306. int ap = header.IndexOf (attr);
  307. if (ap == -1)
  308. return null;
  309. ap += attr.Length;
  310. if (ap >= header.Length)
  311. return null;
  312. char ending = header [ap];
  313. if (ending != '"')
  314. ending = ' ';
  315. int end = header.IndexOf (ending, ap+1);
  316. if (end == -1)
  317. return (ending == '"') ? null : header.Substring (ap);
  318. return header.Substring (ap+1, end-ap-1);
  319. }
  320. public Encoding ContentEncoding {
  321. get {
  322. if (encoding == null){
  323. if (worker_request == null)
  324. throw HttpException.NewWithCode ("No HttpWorkerRequest", WebEventCodes.RuntimeErrorRequestAbort);
  325. string content_type = ContentType;
  326. string parameter = GetParameter (content_type, "; charset=");
  327. if (parameter == null) {
  328. encoding = WebEncoding.RequestEncoding;
  329. } else {
  330. try {
  331. // Do what the #1 web server does
  332. encoding = Encoding.GetEncoding (parameter);
  333. } catch {
  334. encoding = WebEncoding.RequestEncoding;
  335. }
  336. }
  337. }
  338. return encoding;
  339. }
  340. set {
  341. encoding = value;
  342. }
  343. }
  344. public int ContentLength {
  345. get {
  346. if (content_length == -1){
  347. if (worker_request == null)
  348. return 0;
  349. string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
  350. if (cl != null) {
  351. try {
  352. content_length = Int32.Parse (cl);
  353. } catch { }
  354. }
  355. }
  356. // content_length will still be < 0, but we know we gotta read from the client
  357. if (content_length < 0)
  358. return 0;
  359. return content_length;
  360. }
  361. }
  362. public string ContentType {
  363. get {
  364. if (content_type == null){
  365. if (worker_request != null)
  366. content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
  367. if (content_type == null)
  368. content_type = String.Empty;
  369. }
  370. return content_type;
  371. }
  372. set {
  373. content_type = value;
  374. }
  375. }
  376. public HttpCookieCollection Cookies {
  377. get {
  378. if (cookies == null) {
  379. if (worker_request == null) {
  380. cookies = new HttpCookieCollection ();
  381. } else {
  382. string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
  383. cookies = new HttpCookieCollection (cookie_hv);
  384. }
  385. }
  386. #if TARGET_J2EE
  387. // For J2EE portal support we emulate cookies using the session.
  388. GetSessionCookiesForPortal (cookies);
  389. #endif
  390. bool needValidation = validate_cookies;
  391. #if NET_4_0
  392. needValidation |= validateRequestNewMode;
  393. #endif
  394. if (needValidation && !checked_cookies) {
  395. // Setting this before calling the validator prevents
  396. // possible endless recursion
  397. checked_cookies = true;
  398. ValidateCookieCollection (cookies);
  399. }
  400. return cookies;
  401. }
  402. }
  403. public string CurrentExecutionFilePath {
  404. get {
  405. if (current_exe_path != null)
  406. return current_exe_path;
  407. return FilePath;
  408. }
  409. }
  410. #if NET_4_0
  411. public string CurrentExecutionFilePathExtension {
  412. get { return global::System.IO.Path.GetExtension (CurrentExecutionFilePath); }
  413. }
  414. #endif
  415. public string AppRelativeCurrentExecutionFilePath {
  416. get {
  417. return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
  418. }
  419. }
  420. public string FilePath {
  421. get {
  422. if (worker_request == null)
  423. return "/"; // required for 2.0
  424. if (file_path == null)
  425. file_path = UrlUtils.Canonic (ApplyUrlMapping (worker_request.GetFilePath ()));
  426. return file_path;
  427. }
  428. }
  429. internal string ClientFilePath {
  430. get {
  431. if (client_file_path == null) {
  432. if (worker_request == null)
  433. return "/";
  434. return UrlUtils.Canonic (ApplyUrlMapping (worker_request.GetFilePath ()));
  435. }
  436. return client_file_path;
  437. }
  438. set {
  439. if (value == null || value.Length == 0)
  440. client_file_path = null;
  441. else
  442. client_file_path = value;
  443. }
  444. }
  445. internal string BaseVirtualDir {
  446. get {
  447. if (base_virtual_dir == null){
  448. base_virtual_dir = FilePath;
  449. if (UrlUtils.HasSessionId (base_virtual_dir))
  450. base_virtual_dir = UrlUtils.RemoveSessionId (VirtualPathUtility.GetDirectory (base_virtual_dir), base_virtual_dir);
  451. int p = base_virtual_dir.LastIndexOf ('/');
  452. if (p != -1) {
  453. if (p == 0)
  454. p = 1;
  455. base_virtual_dir = base_virtual_dir.Substring (0, p);
  456. } else
  457. base_virtual_dir = "/";
  458. }
  459. return base_virtual_dir;
  460. }
  461. }
  462. public HttpFileCollection Files {
  463. get {
  464. if (files == null) {
  465. files = new HttpFileCollection ();
  466. if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
  467. form = new WebROCollection ();
  468. LoadMultiPart ();
  469. form.Protect ();
  470. }
  471. }
  472. return files;
  473. }
  474. }
  475. public Stream Filter {
  476. get {
  477. if (filter != null)
  478. return filter;
  479. if (input_filter == null)
  480. input_filter = new InputFilterStream ();
  481. return input_filter;
  482. }
  483. set {
  484. // This checks that get_ was called before.
  485. if (input_filter == null)
  486. throw new HttpException ("Invalid filter");
  487. filter = value;
  488. }
  489. }
  490. // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
  491. static Stream GetSubStream (Stream stream)
  492. {
  493. #if !TARGET_JVM
  494. if (stream is IntPtrStream)
  495. return new IntPtrStream (stream);
  496. #endif
  497. if (stream is MemoryStream) {
  498. MemoryStream other = (MemoryStream) stream;
  499. return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
  500. }
  501. if (stream is TempFileStream) {
  502. ((TempFileStream) stream).SavePosition ();
  503. return stream;
  504. }
  505. throw new NotSupportedException ("The stream is " + stream.GetType ());
  506. }
  507. static void EndSubStream (Stream stream)
  508. {
  509. if (stream is TempFileStream) {
  510. ((TempFileStream) stream).RestorePosition ();
  511. }
  512. }
  513. //
  514. // Loads the data on the form for multipart/form-data
  515. //
  516. void LoadMultiPart ()
  517. {
  518. string boundary = GetParameter (ContentType, "; boundary=");
  519. if (boundary == null)
  520. return;
  521. Stream input = GetSubStream (InputStream);
  522. HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
  523. HttpMultipart.Element e;
  524. while ((e = multi_part.ReadNextElement ()) != null) {
  525. if (e.Filename == null){
  526. byte [] copy = new byte [e.Length];
  527. input.Position = e.Start;
  528. input.Read (copy, 0, (int) e.Length);
  529. form.Add (e.Name, ContentEncoding.GetString (copy));
  530. } else {
  531. //
  532. // We use a substream, as in 2.x we will support large uploads streamed to disk,
  533. //
  534. HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
  535. files.AddFile (e.Name, sub);
  536. }
  537. }
  538. EndSubStream (input);
  539. }
  540. //
  541. // Adds the key/value to the form, and sets the argumets to empty
  542. //
  543. void AddRawKeyValue (StringBuilder key, StringBuilder value)
  544. {
  545. string decodedKey = HttpUtility.UrlDecode (key.ToString (), ContentEncoding);
  546. form.Add (decodedKey,
  547. HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
  548. key.Length = 0;
  549. value.Length = 0;
  550. }
  551. //
  552. // Loads the form data from on a application/x-www-form-urlencoded post
  553. //
  554. #if TARGET_J2EE
  555. void RawLoadWwwForm ()
  556. #else
  557. void LoadWwwForm ()
  558. #endif
  559. {
  560. using (Stream input = GetSubStream (InputStream)) {
  561. using (StreamReader s = new StreamReader (input, ContentEncoding)) {
  562. StringBuilder key = new StringBuilder ();
  563. StringBuilder value = new StringBuilder ();
  564. int c;
  565. while ((c = s.Read ()) != -1){
  566. if (c == '='){
  567. value.Length = 0;
  568. while ((c = s.Read ()) != -1){
  569. if (c == '&'){
  570. AddRawKeyValue (key, value);
  571. break;
  572. } else
  573. value.Append ((char) c);
  574. }
  575. if (c == -1){
  576. AddRawKeyValue (key, value);
  577. return;
  578. }
  579. } else if (c == '&')
  580. AddRawKeyValue (key, value);
  581. else
  582. key.Append ((char) c);
  583. }
  584. if (c == -1)
  585. AddRawKeyValue (key, value);
  586. EndSubStream (input);
  587. }
  588. }
  589. }
  590. bool IsContentType (string ct, bool starts_with)
  591. {
  592. if (starts_with)
  593. return StrUtils.StartsWith (ContentType, ct, true);
  594. return String.Compare (ContentType, ct, true, Helpers.InvariantCulture) == 0;
  595. }
  596. internal WebROCollection FormUnvalidated {
  597. get {
  598. if (form == null){
  599. form = new WebROCollection ();
  600. files = new HttpFileCollection ();
  601. if (IsContentType ("multipart/form-data", true))
  602. LoadMultiPart ();
  603. else if (
  604. IsContentType ("application/x-www-form-urlencoded", true))
  605. LoadWwwForm ();
  606. form.Protect ();
  607. }
  608. return form;
  609. }
  610. }
  611. public NameValueCollection Form {
  612. get {
  613. NameValueCollection form = FormUnvalidated;
  614. #if NET_4_0
  615. if (validateRequestNewMode && !checked_form) {
  616. if (!lazyFormValidation) {
  617. // Setting this before calling the validator prevents
  618. // possible endless recursion
  619. checked_form = true;
  620. ValidateNameValueCollection ("Form", form, RequestValidationSource.Form);
  621. }
  622. } else
  623. #endif
  624. if (validate_form && !checked_form){
  625. checked_form = true;
  626. ValidateNameValueCollection ("Form", form);
  627. }
  628. return form;
  629. }
  630. }
  631. public NameValueCollection Headers {
  632. get {
  633. if (headers == null) {
  634. headers = new HeadersCollection (this);
  635. #if NET_4_0
  636. if (validateRequestNewMode) {
  637. RequestValidator validator = RequestValidator.Current;
  638. int validationFailureIndex;
  639. foreach (string hkey in headers.AllKeys) {
  640. string value = headers [hkey];
  641. if (!validator.IsValidRequestString (HttpContext.Current, value, RequestValidationSource.Headers, hkey, out validationFailureIndex))
  642. ThrowValidationException ("Headers", hkey, value);
  643. }
  644. }
  645. #endif
  646. }
  647. return headers;
  648. }
  649. }
  650. public string HttpMethod {
  651. get {
  652. if (http_method == null){
  653. if (worker_request != null)
  654. http_method = worker_request.GetHttpVerbName ();
  655. else
  656. http_method = "GET";
  657. }
  658. return http_method;
  659. }
  660. }
  661. void DoFilter (byte [] buffer)
  662. {
  663. if (input_filter == null || filter == null)
  664. return;
  665. if (buffer.Length < 1024)
  666. buffer = new byte [1024];
  667. // Replace the input with the filtered input
  668. input_filter.BaseStream = input_stream;
  669. MemoryStream ms = new MemoryStream ();
  670. while (true) {
  671. int n = filter.Read (buffer, 0, buffer.Length);
  672. if (n <= 0)
  673. break;
  674. ms.Write (buffer, 0, n);
  675. }
  676. // From now on input_stream has the filtered input
  677. input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
  678. }
  679. #if !TARGET_JVM
  680. const int INPUT_BUFFER_SIZE = 32*1024;
  681. TempFileStream GetTempStream ()
  682. {
  683. string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  684. TempFileStream f = null;
  685. string path;
  686. Random rnd = new Random ();
  687. int num;
  688. do {
  689. num = rnd.Next ();
  690. num++;
  691. path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
  692. try {
  693. f = new TempFileStream (path);
  694. } catch (SecurityException) {
  695. // avoid an endless loop
  696. throw;
  697. } catch { }
  698. } while (f == null);
  699. return f;
  700. }
  701. void MakeInputStream ()
  702. {
  703. if (input_stream != null)
  704. return;
  705. if (worker_request == null) {
  706. input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
  707. DoFilter (new byte [1024]);
  708. return;
  709. }
  710. //
  711. // Use an unmanaged memory block as this might be a large
  712. // upload
  713. //
  714. int content_length = ContentLength;
  715. int content_length_kb = content_length / 1024;
  716. HttpRuntimeSection config = HttpRuntime.Section;
  717. if (content_length_kb > config.MaxRequestLength)
  718. throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
  719. int total = 0;
  720. byte [] buffer;
  721. buffer = worker_request.GetPreloadedEntityBody ();
  722. // we check the instance field 'content_length' here, not the local var.
  723. if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
  724. if (buffer == null || content_length == 0) {
  725. input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
  726. } else {
  727. input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
  728. }
  729. DoFilter (new byte [1024]);
  730. return;
  731. }
  732. if (buffer != null)
  733. total = buffer.Length;
  734. if (content_length > 0 && content_length_kb >= config.RequestLengthDiskThreshold) {
  735. // Writes the request to disk
  736. total = Math.Min (content_length, total);
  737. request_file = GetTempStream ();
  738. Stream output = request_file;
  739. if (total > 0)
  740. output.Write (buffer, 0, total);
  741. if (total < content_length) {
  742. buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
  743. do {
  744. int n;
  745. int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
  746. n = worker_request.ReadEntityBody (buffer, min);
  747. if (n <= 0)
  748. break;
  749. output.Write (buffer, 0, n);
  750. total += n;
  751. } while (total < content_length);
  752. }
  753. request_file.SetReadOnly ();
  754. input_stream = request_file;
  755. } else if (content_length > 0) {
  756. // Buffers the request in an IntPtrStream
  757. total = Math.Min (content_length, total);
  758. IntPtr content = Marshal.AllocHGlobal (content_length);
  759. if (content == (IntPtr) 0)
  760. throw HttpException.NewWithCode (
  761. String.Format ("Not enough memory to allocate {0} bytes.", content_length),
  762. WebEventCodes.WebErrorOtherError);
  763. if (total > 0)
  764. Marshal.Copy (buffer, 0, content, total);
  765. if (total < content_length) {
  766. buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
  767. do {
  768. int n;
  769. int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
  770. n = worker_request.ReadEntityBody (buffer, min);
  771. if (n <= 0)
  772. break;
  773. Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
  774. total += n;
  775. } while (total < content_length);
  776. }
  777. input_stream = new IntPtrStream (content, total);
  778. } else {
  779. // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
  780. MemoryStream ms = new MemoryStream ();
  781. Stream output = ms;
  782. if (total > 0)
  783. ms.Write (buffer, 0, total);
  784. buffer = new byte [INPUT_BUFFER_SIZE];
  785. long maxlength = config.MaxRequestLength * 1024L;
  786. long disk_th = config.RequestLengthDiskThreshold * 1024L;
  787. int n;
  788. while (true) {
  789. n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
  790. if (n <= 0)
  791. break;
  792. total += n;
  793. if (total < 0 || total > maxlength)
  794. throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
  795. if (ms != null && total > disk_th) {
  796. // Swith to on-disk file.
  797. request_file = GetTempStream ();
  798. ms.WriteTo (request_file);
  799. ms = null;
  800. output = request_file;
  801. }
  802. output.Write (buffer, 0, n);
  803. }
  804. if (ms != null) {
  805. input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
  806. } else {
  807. request_file.SetReadOnly ();
  808. input_stream = request_file;
  809. }
  810. }
  811. DoFilter (buffer);
  812. if (total < content_length)
  813. throw HttpException.NewWithCode (411, "The request body is incomplete.", WebEventCodes.WebErrorOtherError);
  814. }
  815. #endif
  816. internal void ReleaseResources ()
  817. {
  818. Stream stream;
  819. if (input_stream != null){
  820. stream = input_stream;
  821. input_stream = null;
  822. try {
  823. stream.Close ();
  824. } catch {}
  825. }
  826. if (request_file != null) {
  827. stream = request_file;
  828. request_file = null;
  829. try {
  830. stream.Close ();
  831. } catch {}
  832. }
  833. }
  834. #if NET_4_0
  835. public RequestContext RequestContext {
  836. get {
  837. if (requestContext == null)
  838. requestContext = new RequestContext (new HttpContextWrapper (this.context ?? HttpContext.Current), new RouteData ());
  839. return requestContext;
  840. }
  841. internal set { requestContext = value; }
  842. }
  843. public ChannelBinding HttpChannelBinding {
  844. get {
  845. throw new PlatformNotSupportedException ("This property is not supported.");
  846. }
  847. }
  848. public Stream GetBufferlessInputStream ()
  849. {
  850. if (bufferlessInputStream == null) {
  851. if (input_stream != null)
  852. throw new HttpException ("Input stream has already been created");
  853. // we don't need to hook up the filter here, because the raw stream should be returned
  854. bufferlessInputStream = new BufferlessInputStream (this);
  855. }
  856. return bufferlessInputStream;
  857. }
  858. //
  859. // Stream that returns the data as it is read, without buffering
  860. //
  861. class BufferlessInputStream : Stream {
  862. HttpRequest request;
  863. // cached, the request content-length
  864. int content_length;
  865. // buffer that holds preloaded data
  866. byte [] preloadedBuffer;
  867. // indicates if we already served the whole preloaded buffer
  868. bool preloaded_served;
  869. // indicates if we already checked the request content-length against httpRuntime limit
  870. bool checked_maxRequestLength;
  871. // our stream position
  872. long position;
  873. //
  874. // @request: the containing request that created us, used to find out content length
  875. public BufferlessInputStream (HttpRequest request)
  876. {
  877. this.request = request;
  878. content_length = request.ContentLength;
  879. }
  880. public override bool CanRead {
  881. get { return true; }
  882. }
  883. public override bool CanSeek {
  884. get { return false; }
  885. }
  886. public override bool CanWrite {
  887. get { return false; }
  888. }
  889. public override long Length {
  890. get {
  891. return content_length;
  892. }
  893. }
  894. public override long Position {
  895. get {
  896. return position;
  897. }
  898. set {
  899. throw new NotSupportedException ("This is a readonly stream");
  900. }
  901. }
  902. public override void Flush ()
  903. {
  904. }
  905. public override int Read (byte [] buffer, int offset, int count)
  906. {
  907. if (buffer == null)
  908. throw new ArgumentNullException ("buffer");
  909. if (offset < 0 || count < 0)
  910. throw new ArgumentOutOfRangeException ("offset or count less than zero.");
  911. if (buffer.Length - offset < count )
  912. throw new ArgumentException ("offset+count",
  913. "The size of the buffer is less than offset + count.");
  914. if (count == 0 || request.worker_request == null)
  915. return 0;
  916. if (!checked_maxRequestLength) {
  917. int content_length_kb = content_length / 1024;
  918. HttpRuntimeSection config = HttpRuntime.Section;
  919. if (content_length_kb > config.MaxRequestLength)
  920. throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
  921. else
  922. checked_maxRequestLength = true;
  923. }
  924. // Serve the bytes we might have preloaded already.
  925. if (!preloaded_served) {
  926. if (preloadedBuffer == null)
  927. preloadedBuffer = request.worker_request.GetPreloadedEntityBody ();
  928. if (preloadedBuffer != null) {
  929. long bytes_left = preloadedBuffer.Length-position;
  930. int n = (int) Math.Min (count, bytes_left);
  931. Array.Copy (preloadedBuffer, position, buffer, offset, n);
  932. position += n;
  933. if (n == bytes_left)
  934. preloaded_served = true;
  935. return n;
  936. }
  937. else
  938. preloaded_served = true;
  939. }
  940. // serve bytes from worker request if available
  941. if (position < content_length) {
  942. long bytes_left = content_length-position;
  943. int n = count;
  944. if (bytes_left < count)
  945. n = (int) bytes_left;
  946. int bytes_read = request.worker_request.ReadEntityBody (buffer, offset, n);
  947. position += bytes_read;
  948. return bytes_read;
  949. }
  950. return 0;
  951. }
  952. public override long Seek (long offset, SeekOrigin origin)
  953. {
  954. throw new NotSupportedException ("Can not seek on the HttpRequest.BufferlessInputStream");
  955. }
  956. public override void SetLength (long value)
  957. {
  958. throw new NotSupportedException ("Can not set length on the HttpRequest.BufferlessInputStream");
  959. }
  960. public override void Write (byte [] buffer, int offset, int count)
  961. {
  962. throw new NotSupportedException ("Can not write on the HttpRequest.BufferlessInputStream");
  963. }
  964. //
  965. // TODO: explicitly support the async methods if there is a convenient way of doing it
  966. //
  967. }
  968. #endif
  969. public Stream InputStream {
  970. get {
  971. if (input_stream == null)
  972. MakeInputStream ();
  973. return input_stream;
  974. }
  975. }
  976. public bool IsAuthenticated {
  977. get {
  978. if (context.User == null || context.User.Identity == null)
  979. return false;
  980. return context.User.Identity.IsAuthenticated;
  981. }
  982. }
  983. public bool IsSecureConnection {
  984. get {
  985. if (worker_request == null)
  986. return false;
  987. return worker_request.IsSecure ();
  988. }
  989. }
  990. public string this [string key] {
  991. [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
  992. get {
  993. // "The QueryString, Form, Cookies, or ServerVariables collection member
  994. // specified in the key parameter."
  995. string val = QueryString [key];
  996. if (val == null)
  997. val = Form [key];
  998. if (val == null) {
  999. HttpCookie cookie = Cookies [key];
  1000. if (cookie != null)
  1001. val = cookie.Value;
  1002. }
  1003. if (val == null)
  1004. val = ServerVariables [key];
  1005. return val;
  1006. }
  1007. }
  1008. public NameValueCollection Params {
  1009. [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
  1010. get {
  1011. if (all_params == null)
  1012. all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
  1013. return all_params;
  1014. }
  1015. }
  1016. internal string PathNoValidation {
  1017. get {
  1018. if (original_path == null) {
  1019. if (url_components != null)
  1020. // use only if it's already been instantiated, so that we can't go into endless
  1021. // recursion in some scenarios
  1022. original_path = UrlComponents.Path;
  1023. else
  1024. original_path = ApplyUrlMapping (worker_request.GetUriPath ());
  1025. }
  1026. return original_path;
  1027. }
  1028. }
  1029. public string Path {
  1030. get {
  1031. if (unescaped_path == null) {
  1032. unescaped_path = PathNoValidation;
  1033. #if NET_4_0
  1034. if (validateRequestNewMode) {
  1035. RequestValidator validator = RequestValidator.Current;
  1036. int validationFailureIndex;
  1037. if (!validator.IsValidRequestString (HttpContext.Current, unescaped_path, RequestValidationSource.Path, null, out validationFailureIndex))
  1038. ThrowValidationException ("Path", "Path", unescaped_path);
  1039. }
  1040. #endif
  1041. }
  1042. return unescaped_path;
  1043. }
  1044. }
  1045. public string PathInfo {
  1046. get {
  1047. if (path_info == null) {
  1048. if (worker_request == null)
  1049. return String.Empty;
  1050. path_info = worker_request.GetPathInfo () ?? String.Empty;
  1051. #if NET_4_0
  1052. if (validateRequestNewMode) {
  1053. RequestValidator validator = RequestValidator.Current;
  1054. int validationFailureIndex;
  1055. if (!validator.IsValidRequestString (HttpContext.Current, path_info, RequestValidationSource.PathInfo, null, out validationFailureIndex))
  1056. ThrowValidationException ("PathInfo", "PathInfo", path_info);
  1057. }
  1058. #endif
  1059. }
  1060. return path_info;
  1061. }
  1062. }
  1063. public string PhysicalApplicationPath {
  1064. get {
  1065. if (worker_request == null)
  1066. throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
  1067. string path = HttpRuntime.AppDomainAppPath;
  1068. if (SecurityManager.SecurityEnabled) {
  1069. new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
  1070. }
  1071. return path;
  1072. }
  1073. }
  1074. public string PhysicalPath {
  1075. get {
  1076. if (worker_request == null)
  1077. return String.Empty; // don't check security with an empty string!
  1078. if (physical_path == null) {
  1079. // Don't call HttpRequest.MapPath here, as that one *trims* the input
  1080. physical_path = worker_request.MapPath (FilePath);
  1081. }
  1082. if (SecurityManager.SecurityEnabled) {
  1083. new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
  1084. }
  1085. return physical_path;
  1086. }
  1087. }
  1088. internal string RootVirtualDir {
  1089. get {
  1090. if (root_virtual_dir == null){
  1091. string fp = FilePath;
  1092. int p = fp.LastIndexOf ('/');
  1093. if (p < 1)
  1094. root_virtual_dir = "/";
  1095. else
  1096. root_virtual_dir = fp.Substring (0, p);
  1097. }
  1098. return root_virtual_dir;
  1099. }
  1100. }
  1101. internal WebROCollection QueryStringUnvalidated {
  1102. get {
  1103. if (query_string_nvc == null) {
  1104. query_string_nvc = new WebROCollection ();
  1105. string q = UrlComponents.Query;
  1106. if (q != null) {
  1107. if (q.Length != 0)
  1108. q = q.Remove(0, 1);
  1109. HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
  1110. }
  1111. query_string_nvc.Protect();
  1112. }
  1113. return query_string_nvc;
  1114. }
  1115. }
  1116. public NameValueCollection QueryString {
  1117. get {
  1118. NameValueCollection query_string_nvc = QueryStringUnvalidated;
  1119. #if NET_4_0
  1120. if (validateRequestNewMode && !checked_query_string) {
  1121. if (!lazyQueryStringValidation) {
  1122. // Setting this before calling the validator prevents
  1123. // possible endless recursion
  1124. checked_query_string = true;
  1125. ValidateNameValueCollection ("QueryString", query_string_nvc, RequestValidationSource.QueryString);
  1126. }
  1127. } else
  1128. #endif
  1129. if (validate_query_string && !checked_query_string) {
  1130. // Setting this before calling the validator prevents
  1131. // possible endless recursion
  1132. checked_query_string = true;
  1133. ValidateNameValueCollection ("QueryString", query_string_nvc);
  1134. }
  1135. return query_string_nvc;
  1136. }
  1137. }
  1138. public string RawUrl {
  1139. get {
  1140. if (raw_url == null) {
  1141. if (worker_request != null)
  1142. raw_url = worker_request.GetRawUrl ();
  1143. else
  1144. raw_url = UrlComponents.Path + UrlComponents.Query;
  1145. if (raw_url == null)
  1146. raw_url = String.Empty;
  1147. #if NET_4_0
  1148. if (validateRequestNewMode) {
  1149. RequestValidator validator = RequestValidator.Current;
  1150. int validationFailureIndex;
  1151. if (!validator.IsValidRequestString (HttpContext.Current, raw_url, RequestValidationSource.RawUrl, null, out validationFailureIndex))
  1152. ThrowValidationException ("RawUrl", "RawUrl", raw_url);
  1153. }
  1154. #endif
  1155. }
  1156. return raw_url;
  1157. }
  1158. }
  1159. //
  1160. // "GET" or "SET"
  1161. //
  1162. public string RequestType {
  1163. get {
  1164. if (request_type == null){
  1165. if (worker_request != null) {
  1166. request_type = worker_request.GetHttpVerbName ();
  1167. http_method = request_type;
  1168. } else {
  1169. request_type = "GET";
  1170. }
  1171. }
  1172. return request_type;
  1173. }
  1174. set {
  1175. request_type = value;
  1176. }
  1177. }
  1178. public NameValueCollection ServerVariables {
  1179. [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
  1180. get {
  1181. if (server_variables == null)
  1182. server_variables = new ServerVariablesCollection (this);
  1183. return server_variables;
  1184. }
  1185. }
  1186. public int TotalBytes {
  1187. get {
  1188. Stream ins = InputStream;
  1189. return (int) ins.Length;
  1190. }
  1191. }
  1192. public Uri Url {
  1193. get {
  1194. if (cached_url == null) {
  1195. if (orig_url == null)
  1196. cached_url = UrlComponents.Uri;
  1197. else
  1198. cached_url = new Uri (orig_url);
  1199. }
  1200. return cached_url;
  1201. }
  1202. }
  1203. public Uri UrlReferrer {
  1204. get {
  1205. if (worker_request == null)
  1206. return null;
  1207. string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
  1208. if (hr == null)
  1209. return null;
  1210. Uri uri = null;
  1211. try {
  1212. uri = new Uri (hr);
  1213. } catch (UriFormatException) {}
  1214. return uri;
  1215. }
  1216. }
  1217. public string UserAgent {
  1218. get {
  1219. if (worker_request == null)
  1220. return null;
  1221. return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
  1222. }
  1223. }
  1224. public string UserHostAddress {
  1225. get {
  1226. if (worker_request == null)
  1227. return null;
  1228. return worker_request.GetRemoteAddress ();
  1229. }
  1230. }
  1231. public string UserHostName {
  1232. get {
  1233. if (worker_request == null)
  1234. return null;
  1235. return worker_request.GetRemoteName ();
  1236. }
  1237. }
  1238. public string [] UserLanguages {
  1239. get {
  1240. if (worker_request == null)
  1241. return null;
  1242. if (user_languages == null)
  1243. user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
  1244. return user_languages;
  1245. }
  1246. }
  1247. public byte [] BinaryRead (int count)
  1248. {
  1249. if (count < 0)
  1250. throw new ArgumentException ("count is < 0");
  1251. Stream s = InputStream;
  1252. byte [] ret = new byte [count];
  1253. if (s.Read (ret, 0, count) != count)
  1254. throw new ArgumentException (
  1255. String.Format ("count {0} exceeds length of available input {1}",
  1256. count, s.Length - s.Position));
  1257. return ret;
  1258. }
  1259. public int [] MapImageCoordinates (string imageFieldName)
  1260. {
  1261. string method = HttpMethod;
  1262. NameValueCollection coll = null;
  1263. if (method == "HEAD" || method == "GET")
  1264. coll = QueryString;
  1265. else if (method == "POST")
  1266. coll = Form;
  1267. if (coll == null)
  1268. return null;
  1269. string x = coll [imageFieldName + ".x"];
  1270. if (x == null || x == "")
  1271. return null;
  1272. string y = coll [imageFieldName + ".y"];
  1273. if (y == null || y == "")
  1274. return null;
  1275. int [] result = new int [2];
  1276. try {
  1277. result [0] = Int32.Parse (x);
  1278. result [1] = Int32.Parse (y);
  1279. } catch {
  1280. return null;
  1281. }
  1282. return result;
  1283. }
  1284. public string MapPath (string virtualPath)
  1285. {
  1286. if (worker_request == null)
  1287. return null;
  1288. return MapPath (virtualPath, BaseVirtualDir, true);
  1289. }
  1290. public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
  1291. {
  1292. if (worker_request == null)
  1293. throw HttpException.NewWithCode ("No HttpWorkerRequest", WebEventCodes.RuntimeErrorRequestAbort);
  1294. if (virtualPath == null)
  1295. virtualPath = "~";
  1296. else {
  1297. virtualPath = virtualPath.Trim ();
  1298. if (virtualPath.Length == 0)
  1299. virtualPath = "~";
  1300. }
  1301. if (!VirtualPathUtility.IsValidVirtualPath (virtualPath))
  1302. throw HttpException.NewWithCode (String.Format ("'{0}' is not a valid virtual path.", virtualPath), WebEventCodes.RuntimeErrorRequestAbort);
  1303. string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
  1304. if (!VirtualPathUtility.IsRooted (virtualPath)) {
  1305. if (StrUtils.IsNullOrEmpty (baseVirtualDir))
  1306. baseVirtualDir = appVirtualPath;
  1307. virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
  1308. if (!VirtualPathUtility.IsAbsolute (virtualPath))
  1309. virtualPath = VirtualPathUtility.ToAbsolute (virtualPath, false);
  1310. } else if (!VirtualPathUtility.IsAbsolute (virtualPath))
  1311. virtualPath = VirtualPathUtility.ToAbsolute (virtualPath, false);
  1312. bool isAppVirtualPath = String.Compare (virtualPath, appVirtualPath, RuntimeHelpers.StringComparison) == 0;
  1313. appVirtualPath = VirtualPathUtility.AppendTrailingSlash (appVirtualPath);
  1314. if (!allowCrossAppMapping){
  1315. if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
  1316. throw new ArgumentException ("MapPath: Mapping across applications not allowed");
  1317. if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
  1318. throw HttpException.NewWithCode ("MapPath: Mapping across applications not allowed", WebEventCodes.RuntimeErrorRequestAbort);
  1319. }
  1320. if (!isAppVirtualPath && !virtualPath.StartsWith (appVirtualPath, RuntimeHelpers.StringComparison))
  1321. throw new InvalidOperationException (String.Format ("Failed to map path '{0}'", virtualPath));
  1322. #if TARGET_JVM
  1323. return worker_request.MapPath (virtualPath);
  1324. #else
  1325. string path = worker_request.MapPath (virtualPath);
  1326. if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
  1327. path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
  1328. return path;
  1329. #endif
  1330. }
  1331. public void SaveAs (string filename, bool includeHeaders)
  1332. {
  1333. Stream output = new FileStream (filename, FileMode.Create);
  1334. if (includeHeaders) {
  1335. StringBuilder sb = new StringBuilder ();
  1336. string version = String.Empty;
  1337. string path = "/";
  1338. if (worker_request != null) {
  1339. version = worker_request.GetHttpVersion ();
  1340. path = UrlComponents.Path;
  1341. }
  1342. string qs = UrlComponents.Query;
  1343. sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
  1344. NameValueCollection coll = Headers;
  1345. foreach (string k in coll.AllKeys) {
  1346. sb.Append (k);
  1347. sb.Append (':');
  1348. sb.Append (coll [k]);
  1349. sb.Append ("\r\n");
  1350. }
  1351. sb.Append ("\r\n");
  1352. // latin1
  1353. byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
  1354. output.Write (bytes, 0, bytes.Length);
  1355. }
  1356. // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
  1357. // to keep InputStream in its state.
  1358. Stream input = GetSubStream (InputStream);
  1359. try {
  1360. long len = input.Length;
  1361. int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
  1362. byte [] data = new byte [buf_size];
  1363. int count = 0;
  1364. while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
  1365. output.Write (data, 0, count);
  1366. len -= count;
  1367. }
  1368. } finally {
  1369. output.Flush ();
  1370. output.Close ();
  1371. EndSubStream (input);
  1372. }
  1373. }
  1374. public void ValidateInput ()
  1375. {
  1376. validate_cookies = true;
  1377. validate_query_string = true;
  1378. validate_form = true;
  1379. #if NET_4_0
  1380. inputValidationEnabled = true;
  1381. #endif
  1382. }
  1383. #if NET_4_0
  1384. internal void Validate ()
  1385. {
  1386. var cfg = HttpRuntime.Section;
  1387. string query = UrlComponents.Query;
  1388. if (query != null && query.Length > cfg.MaxQueryStringLength)
  1389. throw new HttpException (400, "The length of the query string for this request exceeds the configured maxQueryStringLength value.");
  1390. string path = PathNoValidation;
  1391. if (path != null) {
  1392. if (path.Length > cfg.MaxUrlLength)
  1393. throw new HttpException (400, "The length of the URL for this request exceeds the configured maxUrlLength value.");
  1394. char[] invalidChars = RequestPathInvalidCharacters;
  1395. if (invalidChars != null) {
  1396. int idx = path.IndexOfAny (invalidChars);
  1397. if (idx != -1)
  1398. throw HttpException.NewWithCode (
  1399. String.Format ("A potentially dangerous Request.Path value was detected from the client ({0}).", path [idx]),
  1400. WebEventCodes.RuntimeErrorValidationFailure
  1401. );
  1402. }
  1403. }
  1404. if (validateRequestNewMode)
  1405. ValidateInput ();
  1406. }
  1407. #endif
  1408. #region internal routines
  1409. internal string ClientTarget {
  1410. get {
  1411. return client_target;
  1412. }
  1413. set {
  1414. client_target = value;
  1415. }
  1416. }
  1417. public bool IsLocal {
  1418. get {
  1419. string address = worker_request.GetRemoteAddress ();
  1420. if (StrUtils.IsNullOrEmpty (address))
  1421. return false;
  1422. if (address == "127.0.0.1")
  1423. return true;
  1424. System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
  1425. if (System.Net.IPAddress.IsLoopback (remoteAddr))
  1426. return true;
  1427. for (int i = 0; i < host_addresses.Length; i++)
  1428. if (remoteAddr.Equals (host_addresses [i]))
  1429. return true;
  1430. return false;
  1431. }
  1432. }
  1433. internal void SetFilePath (string path)
  1434. {
  1435. file_path = path;
  1436. physical_path = null;
  1437. original_path = null;
  1438. }
  1439. internal void SetCurrentExePath (string path)
  1440. {
  1441. cached_url = null;
  1442. current_exe_path = path;
  1443. UrlComponents.Path = path + PathInfo;
  1444. // recreated on demand
  1445. root_virtual_dir = null;
  1446. base_virtual_dir = null;
  1447. physical_path = null;
  1448. unescaped_path = null;
  1449. original_path = null;
  1450. }
  1451. internal void SetPathInfo (string pi)
  1452. {
  1453. cached_url = null;
  1454. path_info = pi;
  1455. original_path = null;
  1456. string path = UrlComponents.Path;
  1457. UrlComponents.Path = path + PathInfo;
  1458. }
  1459. #if NET_4_0
  1460. internal void SetFormCollection (WebROCollection coll, bool lazyValidation)
  1461. {
  1462. if (coll == null)
  1463. return;
  1464. form = coll;
  1465. lazyFormValidation = lazyValidation;
  1466. }
  1467. internal void SetQueryStringCollection (WebROCollection coll, bool lazyValidation)
  1468. {
  1469. if (coll == null)
  1470. return;
  1471. query_string_nvc = coll;
  1472. lazyQueryStringValidation = lazyValidation;
  1473. }
  1474. #endif
  1475. // Headers is ReadOnly, so we need this hack for cookie-less sessions.
  1476. internal void SetHeader (string name, string value)
  1477. {
  1478. WebROCollection h = (WebROCollection) Headers;
  1479. h.Unprotect ();
  1480. h [name] = value;
  1481. h.Protect ();
  1482. }
  1483. // Notice: there is nothing raw about this querystring.
  1484. internal string QueryStringRaw {
  1485. get {
  1486. UriBuilder urlComponents = UrlComponents;
  1487. if (urlComponents == null) {
  1488. string ret = worker_request.GetQueryString ();
  1489. if (ret == null || ret.Length == 0)
  1490. return String.Empty;
  1491. if (ret [0] == '?')
  1492. return ret;
  1493. return "?" + ret;
  1494. }
  1495. return UrlComponents.Query;
  1496. }
  1497. set {
  1498. UrlComponents.Query = value;
  1499. cached_url = null;
  1500. query_string_nvc = null;
  1501. }
  1502. }
  1503. // Internal, dont know what it does, so flagged as public so we can see it.
  1504. internal void SetForm (WebROCollection coll)
  1505. {
  1506. form = coll;
  1507. }
  1508. internal HttpWorkerRequest WorkerRequest {
  1509. get {
  1510. return worker_request;
  1511. }
  1512. }
  1513. internal HttpContext Context {
  1514. get { return context; }
  1515. set { context = value; }
  1516. }
  1517. static void ValidateNameValueCollection (string name, NameValueCollection coll)
  1518. {
  1519. if (coll == null)
  1520. return;
  1521. foreach (string key in coll.Keys) {
  1522. string val = coll [key];
  1523. if (val != null && val.Length > 0 && IsInvalidString (val))
  1524. ThrowValidationException (name, key, val);
  1525. }
  1526. }
  1527. #if NET_4_0
  1528. static void ValidateNameValueCollection (string name, NameValueCollection coll, RequestValidationSource source)
  1529. {
  1530. if (coll == null)
  1531. return;
  1532. RequestValidator validator = RequestValidator.Current;
  1533. int validationFailureIndex;
  1534. HttpContext context = HttpContext.Current;
  1535. foreach (string key in coll.Keys) {
  1536. string val = coll [key];
  1537. if (val != null && val.Length > 0 && !validator.IsValidRequestString (context, val, source, key, out validationFailureIndex))
  1538. ThrowValidationException (name, key, val);
  1539. }
  1540. }
  1541. [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
  1542. public void InsertEntityBody ()
  1543. {
  1544. throw new PlatformNotSupportedException ("This method is not supported.");
  1545. }
  1546. [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
  1547. public void InsertEntityBody (byte[] buffer, int offset, int count)
  1548. {
  1549. throw new PlatformNotSupportedException ("This method is not supported.");
  1550. }
  1551. #endif
  1552. static void ValidateCookieCollection (HttpCookieCollection cookies)
  1553. {
  1554. if (cookies == null)
  1555. return;
  1556. int size = cookies.Count;
  1557. HttpCookie cookie;
  1558. #if NET_4_0
  1559. RequestValidator validator = RequestValidator.Current;
  1560. int validationFailureIndex;
  1561. HttpContext context = HttpContext.Current;
  1562. #endif
  1563. bool invalid;
  1564. for (int i = 0 ; i < size ; i++) {
  1565. cookie = cookies[i];
  1566. if (cookie == null)
  1567. continue;
  1568. string value = cookie.Value;
  1569. string name = cookie.Name;
  1570. if (!String.IsNullOrEmpty (value)) {
  1571. #if NET_4_0
  1572. if (validateRequestNewMode)
  1573. invalid = !validator.IsValidRequestString (context, value, RequestValidationSource.Cookies, name, out validationFailureIndex);
  1574. else
  1575. #endif
  1576. invalid = IsInvalidString (value);
  1577. if (invalid)
  1578. ThrowValidationException ("Cookies", name, value);
  1579. }
  1580. }
  1581. }
  1582. static void ThrowValidationException (string name, string key, string value)
  1583. {
  1584. string v = "\"" + value + "\"";
  1585. if (v.Length > 20)
  1586. v = v.Substring (0, 16) + "...\"";
  1587. string msg = String.Format ("A potentially dangerous Request.{0} value was " +
  1588. "detected from the client ({1}={2}).", name, key, v);
  1589. throw new HttpRequestValidationException (msg);
  1590. }
  1591. #if NET_4_0
  1592. internal static void ValidateString (string key, string value, RequestValidationSource source)
  1593. {
  1594. if (String.IsNullOrEmpty (value))
  1595. return;
  1596. #pragma warning disable 219
  1597. int ignore;
  1598. #pragma warning restore 219
  1599. if (IsInvalidString (value, out ignore))
  1600. ThrowValidationException (source.ToString (), key, value);
  1601. }
  1602. #endif
  1603. internal static bool IsInvalidString (string val)
  1604. {
  1605. #pragma warning disable 219
  1606. int validationFailureIndex;
  1607. #pragma warning restore 219
  1608. return IsInvalidString (val, out validationFailureIndex);
  1609. }
  1610. internal static bool IsInvalidString (string val, out int validationFailureIndex)
  1611. {
  1612. validationFailureIndex = 0;
  1613. int len = val.Length;
  1614. if (len < 2)
  1615. return false;
  1616. char current = val [0];
  1617. for (int idx = 1; idx < len; idx++) {
  1618. char next = val [idx];
  1619. // See http://secunia.com/advisories/14325
  1620. if (current == '<' || current == '\xff1c') {
  1621. if (next == '!' || next < ' '
  1622. || (next >= 'a' && next <= 'z')
  1623. || (next >= 'A' && next <= 'Z')) {
  1624. validationFailureIndex = idx - 1;
  1625. return true;
  1626. }
  1627. } else if (current == '&' && next == '#') {
  1628. validationFailureIndex = idx - 1;
  1629. return true;
  1630. }
  1631. current = next;
  1632. }
  1633. return false;
  1634. }
  1635. static System.Net.IPAddress [] GetLocalHostAddresses ()
  1636. {
  1637. try {
  1638. string hostName = System.Net.Dns.GetHostName ();
  1639. System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
  1640. return ipaddr;
  1641. } catch {
  1642. return new System.Net.IPAddress[0];
  1643. }
  1644. }
  1645. }
  1646. #endregion
  1647. #region Helper classes
  1648. //
  1649. // Stream-based multipart handling.
  1650. //
  1651. // In this incarnation deals with an HttpInputStream as we are now using
  1652. // IntPtr-based streams instead of byte []. In the future, we will also
  1653. // send uploads above a certain threshold into the disk (to implement
  1654. // limit-less HttpInputFiles).
  1655. //
  1656. class HttpMultipart {
  1657. public class Element {
  1658. public string ContentType;
  1659. public string Name;
  1660. public string Filename;
  1661. public long Start;
  1662. public long Length;
  1663. public override string ToString ()
  1664. {
  1665. return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
  1666. Start.ToString () + ", Length " + Length.ToString ();
  1667. }
  1668. }
  1669. Stream data;
  1670. string boundary;
  1671. byte [] boundary_bytes;
  1672. byte [] buffer;
  1673. bool at_eof;
  1674. Encoding encoding;
  1675. StringBuilder sb;
  1676. const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
  1677. // See RFC 2046
  1678. // In the case of multipart entities, in which one or more different
  1679. // sets of data are combined in a single body, a "multipart" media type
  1680. // field must appear in the entity's header. The body must then contain
  1681. // one or more body parts, each preceded by a boundary delimiter line,
  1682. // and the last one followed by a closing boundary delimiter line.
  1683. // After its boundary delimiter line, each body part then consists of a
  1684. // header area, a blank line, and a body area. Thus a body part is
  1685. // similar to an RFC 822 message in syntax, but different in meaning.
  1686. public HttpMultipart (Stream data, string b, Encoding encoding)
  1687. {
  1688. this.data = data;
  1689. boundary = b;
  1690. boundary_bytes = encoding.GetBytes (b);
  1691. buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
  1692. this.encoding = encoding;
  1693. sb = new StringBuilder ();
  1694. }
  1695. string ReadLine ()
  1696. {
  1697. // CRLF or LF are ok as line endings.
  1698. bool got_cr = false;
  1699. int b = 0;
  1700. sb.Length = 0;
  1701. while (true) {
  1702. b = data.ReadByte ();
  1703. if (b == -1) {
  1704. return null;
  1705. }
  1706. if (b == LF) {
  1707. break;
  1708. }
  1709. got_cr = (b == CR);
  1710. sb.Append ((char) b);
  1711. }
  1712. if (got_cr)
  1713. sb.Length--;
  1714. return sb.ToString ();
  1715. }
  1716. static string GetContentDispositionAttribute (string l, string name)
  1717. {
  1718. int idx = l.IndexOf (name + "=\"");
  1719. if (idx < 0)
  1720. return null;
  1721. int begin = idx + name.Length + "=\"".Length;
  1722. int end = l.IndexOf ('"', begin);
  1723. if (end < 0)
  1724. return null;
  1725. if (begin == end)
  1726. return "";
  1727. return l.Substring (begin, end - begin);
  1728. }
  1729. string GetContentDispositionAttributeWithEncoding (string l, string name)
  1730. {
  1731. int idx = l.IndexOf (name + "=\"");
  1732. if (idx < 0)
  1733. return null;
  1734. int begin = idx + name.Length + "=\"".Length;
  1735. int end = l.IndexOf ('"', begin);
  1736. if (end < 0)
  1737. return null;
  1738. if (begin == end)
  1739. return "";
  1740. string temp = l.Substring (begin, end - begin);
  1741. byte [] source = new byte [temp.Length];
  1742. for (int i = temp.Length - 1; i >= 0; i--)
  1743. source [i] = (byte) temp [i];
  1744. return encoding.GetString (source);
  1745. }
  1746. bool ReadBoundary ()
  1747. {
  1748. try {
  1749. string line = ReadLine ();
  1750. while (line == "")
  1751. line = ReadLine ();
  1752. if (line [0] != '-' || line [1] != '-')
  1753. return false;
  1754. if (!StrUtils.EndsWith (line, boundary, false))
  1755. return true;
  1756. } catch {
  1757. }
  1758. return false;
  1759. }
  1760. string ReadHeaders ()
  1761. {
  1762. string s = ReadLine ();
  1763. if (s == "")
  1764. return null;
  1765. return s;
  1766. }
  1767. bool CompareBytes (byte [] orig, byte [] other)
  1768. {
  1769. for (int i = orig.Length - 1; i >= 0; i--)
  1770. if (orig [i] != other [i])
  1771. return false;
  1772. return true;
  1773. }
  1774. long MoveToNextBoundary ()
  1775. {
  1776. long retval = 0;
  1777. bool got_cr = false;
  1778. int state = 0;
  1779. int c = data.ReadByte ();
  1780. while (true) {
  1781. if (c == -1)
  1782. return -1;
  1783. if (state == 0 && c == LF) {
  1784. retval = data.Position - 1;
  1785. if (got_cr)
  1786. retval--;
  1787. state = 1;
  1788. c = data.ReadByte ();
  1789. } else if (state == 0) {
  1790. got_cr = (c == CR);
  1791. c = data.ReadByte ();
  1792. } else if (state == 1 && c == '-') {
  1793. c = data.ReadByte ();
  1794. if (c == -1)
  1795. return -1;
  1796. if (c != '-') {
  1797. state = 0;
  1798. got_cr = false;
  1799. continue; // no ReadByte() here
  1800. }
  1801. int nread = data.Read (buffer, 0, buffer.Length);
  1802. int bl = buffer.Length;
  1803. if (nread != bl)
  1804. return -1;
  1805. if (!CompareBytes (boundary_bytes, buffer)) {
  1806. state = 0;
  1807. data.Position = retval + 2;
  1808. if (got_cr) {
  1809. data.Position++;
  1810. got_cr = false;
  1811. }
  1812. c = data.ReadByte ();
  1813. continue;
  1814. }
  1815. if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
  1816. at_eof = true;
  1817. } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
  1818. state = 0;
  1819. data.Position = retval + 2;
  1820. if (got_cr) {
  1821. data.Position++;
  1822. got_cr = false;
  1823. }
  1824. c = data.ReadByte ();
  1825. continue;
  1826. }
  1827. data.Position = retval + 2;
  1828. if (got_cr)
  1829. data.Position++;
  1830. break;
  1831. } else {
  1832. // state == 1
  1833. state = 0; // no ReadByte() here
  1834. }
  1835. }
  1836. return retval;
  1837. }
  1838. public Element ReadNextElement ()
  1839. {
  1840. if (at_eof || ReadBoundary ())
  1841. return null;
  1842. Element elem = new Element ();
  1843. string header;
  1844. while ((header = ReadHeaders ()) != null) {
  1845. if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
  1846. elem.Name = GetContentDispositionAttribute (header, "name");
  1847. elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
  1848. } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
  1849. elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
  1850. }
  1851. }
  1852. long start = data.Position;
  1853. elem.Start = start;
  1854. long pos = MoveToNextBoundary ();
  1855. if (pos == -1)
  1856. return null;
  1857. elem.Length = pos - start;
  1858. return elem;
  1859. }
  1860. static string StripPath (string path)
  1861. {
  1862. if (path == null || path.Length == 0)
  1863. return path;
  1864. if (path.IndexOf (":\\") != 1 && !path.StartsWith ("\\\\"))
  1865. return path;
  1866. return path.Substring (path.LastIndexOf ('\\') + 1);
  1867. }
  1868. }
  1869. #endregion
  1870. }