Request.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. // **********************************************************************************
  2. // CassiniDev - http://cassinidev.codeplex.com
  3. //
  4. // Copyright (c) 2010 Sky Sanders. All rights reserved.
  5. // Copyright (c) Microsoft Corporation. All rights reserved.
  6. //
  7. // This source code is subject to terms and conditions of the Microsoft Public
  8. // License (Ms-PL). A copy of the license can be found in the license.txt file
  9. // included in this distribution.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. // **********************************************************************************
  14. #region
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Collections.Specialized;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Reflection;
  22. using System.Security;
  23. using System.Security.Permissions;
  24. using System.Text;
  25. using System.Web;
  26. using System.Web.Hosting;
  27. using Microsoft.Win32.SafeHandles;
  28. #endregion
  29. namespace CassiniDev
  30. {
  31. internal class Request : SimpleWorkerRequest
  32. {
  33. private const int MaxChunkLength = 64 * 1024;
  34. private const int MaxHeaderBytes = 32 * 1024;
  35. private static readonly char[] BadPathChars = new[] { '%', '>', '<', ':', '\\' };
  36. private static readonly string[] DefaultFileNames = new[] { "default.aspx", "default.htm", "default.html" };
  37. private static readonly char[] IntToHex = new[]
  38. {
  39. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  40. };
  41. private static readonly string[] RestrictedDirs = new[]
  42. {
  43. "/bin",
  44. "/app_browsers",
  45. "/app_code",
  46. "/app_data",
  47. "/app_localresources",
  48. "/app_globalresources",
  49. "/app_webreferences"
  50. };
  51. private readonly IStackWalk _connectionPermission = new PermissionSet(PermissionState.Unrestricted);
  52. private readonly Host _host;
  53. private readonly Server _server;
  54. private string _allRawHeaders;
  55. private byte[] _body;
  56. private int _bodyLength;
  57. private Connection _connection;
  58. private int _contentLength;
  59. // security permission to Assert remoting calls to _connection
  60. private int _endHeadersOffset;
  61. private string _filePath;
  62. private byte[] _headerBytes;
  63. private List<ByteString> _headerByteStrings;
  64. private bool _headersSent;
  65. // parsed request data
  66. private bool _isClientScriptPath;
  67. private string[] _knownRequestHeaders;
  68. private string _path;
  69. private string _pathInfo;
  70. private string _pathTranslated;
  71. private string _protocol;
  72. private string _queryString;
  73. private byte[] _queryStringBytes;
  74. private List<byte[]> _responseBodyBytes;
  75. private StringBuilder _responseHeadersBuilder;
  76. private int _responseStatus;
  77. private bool _specialCaseStaticFileHeaders;
  78. private int _startHeadersOffset;
  79. private string[][] _unknownRequestHeaders;
  80. private string _url;
  81. private string _verb;
  82. public Request(Server server, Host host, Connection connection)
  83. : base(String.Empty, String.Empty, null)
  84. {
  85. _connectionPermission = new PermissionSet(PermissionState.Unrestricted);
  86. _server = server;
  87. _host = host;
  88. _connection = connection;
  89. }
  90. public override void CloseConnection()
  91. {
  92. _connectionPermission.Assert();
  93. _connection.Close();
  94. }
  95. public override void EndOfRequest()
  96. {
  97. Connection conn = _connection;
  98. if (conn != null)
  99. {
  100. _connection = null;
  101. _server.OnRequestEnd(conn);
  102. }
  103. }
  104. public override void FlushResponse(bool finalFlush)
  105. {
  106. if (_responseStatus == 404 && !_headersSent && finalFlush && _verb == "GET")
  107. {
  108. // attempt directory listing
  109. if (ProcessDirectoryListingRequest())
  110. {
  111. return;
  112. }
  113. }
  114. _connectionPermission.Assert();
  115. if (!_headersSent)
  116. {
  117. _connection.WriteHeaders(_responseStatus, _responseHeadersBuilder.ToString());
  118. _headersSent = true;
  119. }
  120. foreach (byte[] bytes in _responseBodyBytes)
  121. {
  122. _connection.WriteBody(bytes, 0, bytes.Length);
  123. }
  124. _responseBodyBytes = new List<byte[]>();
  125. if (finalFlush)
  126. {
  127. _connection.Close();
  128. }
  129. }
  130. public override string GetAppPath()
  131. {
  132. return _host.VirtualPath;
  133. }
  134. public override string GetAppPathTranslated()
  135. {
  136. return _host.PhysicalPath;
  137. }
  138. public override string GetFilePath()
  139. {
  140. return _filePath;
  141. }
  142. public override string GetFilePathTranslated()
  143. {
  144. return _pathTranslated;
  145. }
  146. public override string GetHttpVerbName()
  147. {
  148. return _verb;
  149. }
  150. public override string GetHttpVersion()
  151. {
  152. return _protocol;
  153. }
  154. public override string GetKnownRequestHeader(int index)
  155. {
  156. return _knownRequestHeaders[index];
  157. }
  158. public override string GetLocalAddress()
  159. {
  160. _connectionPermission.Assert();
  161. return _connection.LocalIP;
  162. }
  163. public override int GetLocalPort()
  164. {
  165. return _host.Port;
  166. }
  167. public override string GetPathInfo()
  168. {
  169. return _pathInfo;
  170. }
  171. public override byte[] GetPreloadedEntityBody()
  172. {
  173. return _body;
  174. }
  175. public override string GetQueryString()
  176. {
  177. return _queryString;
  178. }
  179. public override byte[] GetQueryStringRawBytes()
  180. {
  181. return _queryStringBytes;
  182. }
  183. public override string GetRawUrl()
  184. {
  185. return _url;
  186. }
  187. public override string GetRemoteAddress()
  188. {
  189. _connectionPermission.Assert();
  190. return _connection.RemoteIP;
  191. }
  192. public override int GetRemotePort()
  193. {
  194. return 0;
  195. }
  196. public override string GetServerName()
  197. {
  198. string localAddress = GetLocalAddress();
  199. if (localAddress.Equals("127.0.0.1"))
  200. {
  201. return "localhost";
  202. }
  203. return localAddress;
  204. }
  205. public override string GetServerVariable(string name)
  206. {
  207. string processUser = string.Empty;
  208. string str2 = name;
  209. if (str2 == null)
  210. {
  211. return processUser;
  212. }
  213. if (str2 != "ALL_RAW")
  214. {
  215. if (str2 != "SERVER_PROTOCOL")
  216. {
  217. if (str2 == "LOGON_USER")
  218. {
  219. if (GetUserToken() != IntPtr.Zero)
  220. {
  221. processUser = _host.GetProcessUser();
  222. }
  223. return processUser;
  224. }
  225. if ((str2 == "AUTH_TYPE") && (GetUserToken() != IntPtr.Zero))
  226. {
  227. processUser = "NTLM";
  228. }
  229. return processUser;
  230. }
  231. }
  232. else
  233. {
  234. return _allRawHeaders;
  235. }
  236. return _protocol;
  237. }
  238. public override string GetUnknownRequestHeader(string name)
  239. {
  240. int n = _unknownRequestHeaders.Length;
  241. for (int i = 0; i < n; i++)
  242. {
  243. if (string.Compare(name, _unknownRequestHeaders[i][0], StringComparison.OrdinalIgnoreCase) == 0)
  244. {
  245. return _unknownRequestHeaders[i][1];
  246. }
  247. }
  248. return null;
  249. }
  250. public override string[][] GetUnknownRequestHeaders()
  251. {
  252. return _unknownRequestHeaders;
  253. }
  254. ///////////////////////////////////////////////////////////////////////////////////////////////
  255. // Implementation of HttpWorkerRequest
  256. public override string GetUriPath()
  257. {
  258. return _path;
  259. }
  260. public override IntPtr GetUserToken()
  261. {
  262. return _host.GetProcessToken();
  263. }
  264. public override bool HeadersSent()
  265. {
  266. return _headersSent;
  267. }
  268. public override bool IsClientConnected()
  269. {
  270. _connectionPermission.Assert();
  271. return _connection.Connected;
  272. }
  273. public override bool IsEntireEntityBodyIsPreloaded()
  274. {
  275. return (_contentLength == _bodyLength);
  276. }
  277. public override string MapPath(string path)
  278. {
  279. string mappedPath;
  280. bool isClientScriptPath;
  281. if (string.IsNullOrEmpty(path) || path.Equals("/"))
  282. {
  283. // asking for the site root
  284. mappedPath = _host.VirtualPath == "/" ? _host.PhysicalPath : Environment.SystemDirectory;
  285. }
  286. else if (_host.IsVirtualPathAppPath(path))
  287. {
  288. // application path
  289. mappedPath = _host.PhysicalPath;
  290. }
  291. else if (_host.IsVirtualPathInApp(path, out isClientScriptPath))
  292. {
  293. if (isClientScriptPath)
  294. {
  295. mappedPath = _host.PhysicalClientScriptPath +
  296. path.Substring(_host.NormalizedClientScriptPath.Length);
  297. }
  298. else
  299. {
  300. // inside app but not the app path itself
  301. mappedPath = _host.PhysicalPath + path.Substring(_host.NormalizedVirtualPath.Length);
  302. }
  303. }
  304. else
  305. {
  306. // outside of app -- make relative to app path
  307. if (path.StartsWith("/", StringComparison.Ordinal))
  308. {
  309. mappedPath = _host.PhysicalPath + path.Substring(1);
  310. }
  311. else
  312. {
  313. mappedPath = _host.PhysicalPath + path;
  314. }
  315. }
  316. mappedPath = mappedPath.Replace('/', '\\');
  317. if (mappedPath.EndsWith("\\", StringComparison.Ordinal) &&
  318. !mappedPath.EndsWith(":\\", StringComparison.Ordinal))
  319. {
  320. mappedPath = mappedPath.Substring(0, mappedPath.Length - 1);
  321. }
  322. return mappedPath;
  323. }
  324. [AspNetHostingPermission(SecurityAction.Assert, Level = AspNetHostingPermissionLevel.Medium)]
  325. public void Process()
  326. {
  327. // read the request
  328. if (!TryParseRequest())
  329. {
  330. return;
  331. }
  332. // 100 response to POST
  333. if (_verb == "POST" && _contentLength > 0 && _bodyLength < _contentLength)
  334. {
  335. _connection.Write100Continue();
  336. }
  337. if (!_host.RequireAuthentication || TryNtlmAuthenticate())
  338. {
  339. // special case for client script
  340. if (_isClientScriptPath)
  341. {
  342. _connection.WriteEntireResponseFromFile(
  343. _host.PhysicalClientScriptPath + _path.Substring(_host.NormalizedClientScriptPath.Length), false);
  344. return;
  345. }
  346. // deny access to code, bin, etc.
  347. if (IsRequestForRestrictedDirectory())
  348. {
  349. _connection.WriteErrorAndClose(403);
  350. return;
  351. }
  352. // special case for a request to a directory (ensure / at the end and process default documents)
  353. if (ProcessDirectoryRequest())
  354. {
  355. return;
  356. }
  357. PrepareResponse();
  358. // Hand the processing over to HttpRuntime
  359. HttpRuntime.ProcessRequest(this);
  360. }
  361. }
  362. public override int ReadEntityBody(byte[] buffer, int size)
  363. {
  364. int bytesRead = 0;
  365. _connectionPermission.Assert();
  366. byte[] bytes = _connection.ReadRequestBytes(size);
  367. if (bytes != null && bytes.Length > 0)
  368. {
  369. bytesRead = bytes.Length;
  370. Buffer.BlockCopy(bytes, 0, buffer, 0, bytesRead);
  371. }
  372. return bytesRead;
  373. }
  374. public override void SendCalculatedContentLength(int contentLength)
  375. {
  376. if (!_headersSent)
  377. {
  378. _responseHeadersBuilder.Append("Content-Length: ");
  379. _responseHeadersBuilder.Append(contentLength.ToString(CultureInfo.InvariantCulture));
  380. _responseHeadersBuilder.Append("\r\n");
  381. }
  382. }
  383. public override void SendKnownResponseHeader(int index, string value)
  384. {
  385. if (_headersSent)
  386. {
  387. return;
  388. }
  389. switch (index)
  390. {
  391. case HeaderServer:
  392. case HeaderDate:
  393. case HeaderConnection:
  394. // ignore these
  395. return;
  396. case HeaderAcceptRanges:
  397. // FIX: #14359
  398. if (value != "bytes")
  399. {
  400. // use this header to detect when we're processing a static file
  401. break;
  402. }
  403. _specialCaseStaticFileHeaders = true;
  404. return;
  405. case HeaderExpires:
  406. case HeaderLastModified:
  407. // FIX: #14359
  408. if (!_specialCaseStaticFileHeaders)
  409. {
  410. // NOTE: Ignore these for static files. These are generated
  411. // by the StaticFileHandler, but they shouldn't be.
  412. break;
  413. }
  414. return;
  415. // FIX: #12506
  416. case HeaderContentType:
  417. string contentType = null;
  418. if (value == "application/octet-stream")
  419. {
  420. // application/octet-stream is default for unknown so lets
  421. // take a shot at determining the type.
  422. // don't do this for other content-types as you are going to
  423. // end up sending text/plain for endpoints that are handled by
  424. // asp.net such as .aspx, .asmx, .axd, etc etc
  425. contentType = CommonExtensions.GetContentType(_pathTranslated);
  426. }
  427. value = contentType ?? value;
  428. break;
  429. }
  430. _responseHeadersBuilder.Append(GetKnownResponseHeaderName(index));
  431. _responseHeadersBuilder.Append(": ");
  432. _responseHeadersBuilder.Append(value);
  433. _responseHeadersBuilder.Append("\r\n");
  434. }
  435. public void SetResponseHeader(string name, string value)
  436. {
  437. _responseHeadersBuilder.Append(name);
  438. _responseHeadersBuilder.Append(": ");
  439. _responseHeadersBuilder.Append(value);
  440. _responseHeadersBuilder.Append("\r\n");
  441. }
  442. public override void SendResponseFromFile(string filename, long offset, long length)
  443. {
  444. if (length == 0)
  445. {
  446. return;
  447. }
  448. FileStream f = null;
  449. try
  450. {
  451. f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  452. SendResponseFromFileStream(f, offset, length);
  453. }
  454. finally
  455. {
  456. if (f != null)
  457. {
  458. f.Close();
  459. }
  460. }
  461. }
  462. public override void SendResponseFromFile(IntPtr handle, long offset, long length)
  463. {
  464. if (length == 0)
  465. {
  466. return;
  467. }
  468. using (var sfh = new SafeFileHandle(handle, false))
  469. {
  470. using (var f = new FileStream(sfh, FileAccess.Read))
  471. {
  472. SendResponseFromFileStream(f, offset, length);
  473. }
  474. }
  475. }
  476. public override void SendResponseFromMemory(byte[] data, int length)
  477. {
  478. if (length > 0)
  479. {
  480. var bytes = new byte[length];
  481. Buffer.BlockCopy(data, 0, bytes, 0, length);
  482. _responseBodyBytes.Add(bytes);
  483. }
  484. }
  485. public override void SendStatus(int statusCode, string statusDescription)
  486. {
  487. _responseStatus = statusCode;
  488. }
  489. public override void SendUnknownResponseHeader(string name, string value)
  490. {
  491. if (_headersSent)
  492. return;
  493. _responseHeadersBuilder.Append(name);
  494. _responseHeadersBuilder.Append(": ");
  495. _responseHeadersBuilder.Append(value);
  496. _responseHeadersBuilder.Append("\r\n");
  497. }
  498. private bool IsBadPath()
  499. {
  500. if (_path.IndexOfAny(BadPathChars) >= 0)
  501. {
  502. return true;
  503. }
  504. if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(_path, "..", CompareOptions.Ordinal) >= 0)
  505. {
  506. return true;
  507. }
  508. if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(_path, "//", CompareOptions.Ordinal) >= 0)
  509. {
  510. return true;
  511. }
  512. return false;
  513. }
  514. private bool IsRequestForRestrictedDirectory()
  515. {
  516. String p = CultureInfo.InvariantCulture.TextInfo.ToLower(_path);
  517. if (_host.VirtualPath != "/")
  518. {
  519. p = p.Substring(_host.VirtualPath.Length);
  520. }
  521. foreach (String dir in RestrictedDirs)
  522. {
  523. if (p.StartsWith(dir, StringComparison.Ordinal))
  524. {
  525. if (p.Length == dir.Length || p[dir.Length] == '/')
  526. {
  527. return true;
  528. }
  529. }
  530. }
  531. return false;
  532. }
  533. private void ParseHeaders()
  534. {
  535. _knownRequestHeaders = new string[RequestHeaderMaximum];
  536. // construct unknown headers as array list of name1,value1,...
  537. var headers = new List<string>();
  538. for (int i = 1; i < _headerByteStrings.Count; i++)
  539. {
  540. string s = _headerByteStrings[i].GetString();
  541. int c = s.IndexOf(':');
  542. if (c >= 0)
  543. {
  544. string name = s.Substring(0, c).Trim();
  545. string value = s.Substring(c + 1).Trim();
  546. // remember
  547. int knownIndex = GetKnownRequestHeaderIndex(name);
  548. if (knownIndex >= 0)
  549. {
  550. _knownRequestHeaders[knownIndex] = value;
  551. }
  552. else
  553. {
  554. headers.Add(name);
  555. headers.Add(value);
  556. }
  557. }
  558. }
  559. // copy to array unknown headers
  560. int n = headers.Count / 2;
  561. _unknownRequestHeaders = new string[n][];
  562. int j = 0;
  563. for (int i = 0; i < n; i++)
  564. {
  565. _unknownRequestHeaders[i] = new string[2];
  566. _unknownRequestHeaders[i][0] = headers[j++];
  567. _unknownRequestHeaders[i][1] = headers[j++];
  568. }
  569. // remember all raw headers as one string
  570. if (_headerByteStrings.Count > 1)
  571. {
  572. _allRawHeaders = Encoding.UTF8.GetString(_headerBytes, _startHeadersOffset,
  573. _endHeadersOffset - _startHeadersOffset);
  574. }
  575. else
  576. {
  577. _allRawHeaders = String.Empty;
  578. }
  579. }
  580. private void ParsePostedContent()
  581. {
  582. _contentLength = 0;
  583. _bodyLength = 0;
  584. string contentLengthValue = _knownRequestHeaders[HeaderContentLength];
  585. if (contentLengthValue != null)
  586. {
  587. try
  588. {
  589. _contentLength = Int32.Parse(contentLengthValue, CultureInfo.InvariantCulture);
  590. }
  591. // ReSharper disable EmptyGeneralCatchClause
  592. catch
  593. // ReSharper restore EmptyGeneralCatchClause
  594. {
  595. }
  596. }
  597. if (_headerBytes.Length > _endHeadersOffset)
  598. {
  599. _bodyLength = _headerBytes.Length - _endHeadersOffset;
  600. if (_bodyLength > _contentLength)
  601. {
  602. _bodyLength = _contentLength; // don't read more than the content-length
  603. }
  604. if (_bodyLength > 0)
  605. {
  606. _body = new byte[_bodyLength];
  607. Buffer.BlockCopy(_headerBytes, _endHeadersOffset, _body, 0, _bodyLength);
  608. _connection.LogRequestBody(_body);
  609. }
  610. }
  611. }
  612. private void ParseRequestLine()
  613. {
  614. ByteString requestLine = _headerByteStrings[0];
  615. ByteString[] elems = requestLine.Split(' ');
  616. if (elems == null || elems.Length < 2 || elems.Length > 3)
  617. {
  618. _connection.WriteErrorAndClose(400);
  619. return;
  620. }
  621. _verb = elems[0].GetString();
  622. ByteString urlBytes = elems[1];
  623. _url = urlBytes.GetString();
  624. _protocol = elems.Length == 3 ? elems[2].GetString() : "HTTP/1.0";
  625. // query string
  626. int iqs = urlBytes.IndexOf('?');
  627. _queryStringBytes = iqs > 0 ? urlBytes.Substring(iqs + 1).GetBytes() : new byte[0];
  628. iqs = _url.IndexOf('?');
  629. if (iqs > 0)
  630. {
  631. _path = _url.Substring(0, iqs);
  632. _queryString = _url.Substring(iqs + 1);
  633. }
  634. else
  635. {
  636. _path = _url;
  637. _queryStringBytes = new byte[0];
  638. }
  639. // url-decode path
  640. if (_path.IndexOf('%') >= 0)
  641. {
  642. _path = HttpUtility.UrlDecode(_path, Encoding.UTF8);
  643. iqs = _url.IndexOf('?');
  644. if (iqs >= 0)
  645. {
  646. _url = _path + _url.Substring(iqs);
  647. }
  648. else
  649. {
  650. _url = _path;
  651. }
  652. }
  653. // path info
  654. int lastDot = _path.LastIndexOf('.');
  655. int lastSlh = _path.LastIndexOf('/');
  656. if (lastDot >= 0 && lastSlh >= 0 && lastDot < lastSlh)
  657. {
  658. int ipi = _path.IndexOf('/', lastDot);
  659. _filePath = _path.Substring(0, ipi);
  660. _pathInfo = _path.Substring(ipi);
  661. }
  662. else
  663. {
  664. _filePath = _path;
  665. _pathInfo = String.Empty;
  666. }
  667. _pathTranslated = MapPath(_filePath);
  668. _connection.LogRequest(_pathTranslated, _url);
  669. }
  670. private void PrepareResponse()
  671. {
  672. _headersSent = false;
  673. _responseStatus = 200;
  674. _responseHeadersBuilder = new StringBuilder();
  675. _responseBodyBytes = new List<byte[]>();
  676. ProcessPlugins();
  677. }
  678. private bool ProcessDirectoryListingRequest()
  679. {
  680. if (_verb != "GET")
  681. {
  682. return false;
  683. }
  684. if (!_server.DisableDirectoryListing)
  685. {
  686. _connection.WriteEntireResponseFromString(200, "Content-type: text/html; charset=utf-8\r\n",
  687. Messages.FormatErrorMessageBody(404,"δÕÒµ½Ä¬ÈÏÒ³"),
  688. false);
  689. return true;
  690. }
  691. String dirPathTranslated = _pathTranslated;
  692. if (_pathInfo.Length > 0)
  693. {
  694. // directory path can never have pathInfo
  695. dirPathTranslated = MapPath(_path);
  696. }
  697. if (!Directory.Exists(dirPathTranslated))
  698. {
  699. return false;
  700. }
  701. // get all files and subdirs
  702. FileSystemInfo[] infos = null;
  703. try
  704. {
  705. infos = (new DirectoryInfo(dirPathTranslated)).GetFileSystemInfos();
  706. }
  707. // ReSharper disable EmptyGeneralCatchClause
  708. catch
  709. // ReSharper restore EmptyGeneralCatchClause
  710. {
  711. }
  712. // determine if parent is appropriate
  713. string parentPath = null;
  714. if (_path.Length > 1)
  715. {
  716. int i = _path.LastIndexOf('/', _path.Length - 2);
  717. parentPath = (i > 0) ? _path.Substring(0, i) : "/";
  718. if (!_host.IsVirtualPathInApp(parentPath))
  719. {
  720. parentPath = null;
  721. }
  722. }
  723. _connection.WriteEntireResponseFromString(200, "Content-type: text/html; charset=utf-8\r\n",
  724. Messages.FormatDirectoryListing(_path, parentPath, infos),
  725. false);
  726. return true;
  727. }
  728. private bool ProcessDirectoryRequest()
  729. {
  730. String dirPathTranslated = _pathTranslated;
  731. if (_pathInfo.Length > 0)
  732. {
  733. // directory path can never have pathInfo
  734. dirPathTranslated = MapPath(_path);
  735. }
  736. if (!Directory.Exists(dirPathTranslated))
  737. {
  738. return false;
  739. }
  740. // have to redirect /foo to /foo/ to allow relative links to work
  741. if (!_path.EndsWith("/", StringComparison.Ordinal))
  742. {
  743. string newPath = _path + "/";
  744. string location = "Location: " + UrlEncodeRedirect(newPath) + "\r\n";
  745. string body = "<html><head><title>Object moved</title></head><body>\r\n" +
  746. "<h2>Object moved to <a href='" + newPath + "'>here</a>.</h2>\r\n" +
  747. "</body></html>\r\n";
  748. _connection.WriteEntireResponseFromString(302, location, body, false);
  749. return true;
  750. }
  751. // check for the default file
  752. foreach (string filename in DefaultFileNames)
  753. {
  754. string defaultFilePath = dirPathTranslated + "\\" + filename;
  755. if (File.Exists(defaultFilePath))
  756. {
  757. // pretend the request is for the default file path
  758. _path += filename;
  759. _filePath = _path;
  760. _url = (_queryString != null) ? (_path + "?" + _queryString) : _path;
  761. _pathTranslated = defaultFilePath;
  762. return false; // go through normal processing
  763. }
  764. }
  765. return false; // go through normal processing
  766. }
  767. private void ReadAllHeaders()
  768. {
  769. _headerBytes = null;
  770. do
  771. {
  772. if (!TryReadAllHeaders())
  773. {
  774. // something bad happened
  775. break;
  776. }
  777. } while (_endHeadersOffset < 0); // found \r\n\r\n
  778. //
  779. // fixed: Item # 13290
  780. if (_headerByteStrings != null && _headerByteStrings.Count > 0)
  781. {
  782. _connection.LogRequestHeaders(string.Join(Environment.NewLine, _headerByteStrings.Select(b => b.GetString()).ToArray()));
  783. }
  784. }
  785. private void Reset()
  786. {
  787. _headerBytes = null;
  788. _startHeadersOffset = 0;
  789. _endHeadersOffset = 0;
  790. _headerByteStrings = null;
  791. _isClientScriptPath = false;
  792. _verb = null;
  793. _url = null;
  794. _protocol = null;
  795. _path = null;
  796. _filePath = null;
  797. _pathInfo = null;
  798. _pathTranslated = null;
  799. _queryString = null;
  800. _queryStringBytes = null;
  801. _contentLength = 0;
  802. _bodyLength = 0;
  803. _body = null;
  804. _allRawHeaders = null;
  805. _unknownRequestHeaders = null;
  806. _knownRequestHeaders = null;
  807. _specialCaseStaticFileHeaders = false;
  808. }
  809. private void SendResponseFromFileStream(Stream f, long offset, long length)
  810. {
  811. long fileSize = f.Length;
  812. if (length == -1)
  813. {
  814. length = fileSize - offset;
  815. }
  816. if (length == 0 || offset < 0 || length > fileSize - offset)
  817. {
  818. return;
  819. }
  820. if (offset > 0)
  821. {
  822. f.Seek(offset, SeekOrigin.Begin);
  823. }
  824. if (length <= MaxChunkLength)
  825. {
  826. var fileBytes = new byte[(int)length];
  827. int bytesRead = f.Read(fileBytes, 0, (int)length);
  828. SendResponseFromMemory(fileBytes, bytesRead);
  829. }
  830. else
  831. {
  832. var chunk = new byte[MaxChunkLength];
  833. var bytesRemaining = (int)length;
  834. while (bytesRemaining > 0)
  835. {
  836. int bytesToRead = (bytesRemaining < MaxChunkLength) ? bytesRemaining : MaxChunkLength;
  837. int bytesRead = f.Read(chunk, 0, bytesToRead);
  838. SendResponseFromMemory(chunk, bytesRead);
  839. bytesRemaining -= bytesRead;
  840. // flush to release keep memory
  841. if ((bytesRemaining > 0) && (bytesRead > 0))
  842. {
  843. FlushResponse(false);
  844. }
  845. }
  846. }
  847. }
  848. private void SkipAllPostedContent()
  849. {
  850. if ((_contentLength > 0) && (_bodyLength < _contentLength))
  851. {
  852. byte[] buffer;
  853. for (int i = _contentLength - _bodyLength; i > 0; i -= buffer.Length)
  854. {
  855. buffer = _connection.ReadRequestBytes(i);
  856. if ((buffer == null) || (buffer.Length == 0))
  857. {
  858. return;
  859. }
  860. }
  861. }
  862. }
  863. [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true),
  864. SecurityPermission(SecurityAction.Assert, ControlPrincipal = true)]
  865. private bool TryNtlmAuthenticate()
  866. {
  867. try
  868. {
  869. using (var auth = new NtlmAuth())
  870. {
  871. do
  872. {
  873. string blobString = null;
  874. string extraHeaders = _knownRequestHeaders[0x18];
  875. if ((extraHeaders != null) && extraHeaders.StartsWith("NTLM ", StringComparison.Ordinal))
  876. {
  877. blobString = extraHeaders.Substring(5);
  878. }
  879. if (blobString != null)
  880. {
  881. if (!auth.Authenticate(blobString))
  882. {
  883. _connection.WriteErrorAndClose(0x193);
  884. return false;
  885. }
  886. if (auth.Completed)
  887. {
  888. goto Label_009A;
  889. }
  890. extraHeaders = "WWW-Authenticate: NTLM " + auth.Blob + "\r\n";
  891. }
  892. else
  893. {
  894. extraHeaders = "WWW-Authenticate: NTLM\r\n";
  895. }
  896. SkipAllPostedContent();
  897. _connection.WriteErrorWithExtraHeadersAndKeepAlive(0x191, extraHeaders);
  898. } while (TryParseRequest());
  899. return false;
  900. Label_009A:
  901. if (_host.GetProcessSid() != auth.SID)
  902. {
  903. _connection.WriteErrorAndClose(0x193);
  904. return false;
  905. }
  906. }
  907. }
  908. catch
  909. {
  910. try
  911. {
  912. _connection.WriteErrorAndClose(500);
  913. }
  914. // ReSharper disable EmptyGeneralCatchClause
  915. catch
  916. // ReSharper restore EmptyGeneralCatchClause
  917. {
  918. }
  919. return false;
  920. }
  921. return true;
  922. }
  923. /// <summary>
  924. /// TODO: defer response until request is written
  925. /// </summary>
  926. /// <returns></returns>
  927. private bool TryParseRequest()
  928. {
  929. Reset();
  930. ReadAllHeaders();
  931. if (_headerBytes == null || _endHeadersOffset < 0 ||
  932. _headerByteStrings == null || _headerByteStrings.Count == 0)
  933. {
  934. _connection.WriteErrorAndClose(400);
  935. return false;
  936. }
  937. ParseRequestLine();
  938. // Check for bad path
  939. if (IsBadPath())
  940. {
  941. _connection.WriteErrorAndClose(400);
  942. return false;
  943. }
  944. // Check if the path is not well formed or is not for the current app
  945. if (!_host.IsVirtualPathInApp(_path, out _isClientScriptPath))
  946. {
  947. _connection.WriteErrorAndClose(404);
  948. return false;
  949. }
  950. ParseHeaders();
  951. ParsePostedContent();
  952. return true;
  953. }
  954. private bool TryReadAllHeaders()
  955. {
  956. // read the first packet (up to 32K)
  957. byte[] headerBytes = _connection.ReadRequestBytes(MaxHeaderBytes);
  958. if (headerBytes == null || headerBytes.Length == 0)
  959. return false;
  960. if (_headerBytes != null)
  961. {
  962. // previous partial read
  963. int len = headerBytes.Length + _headerBytes.Length;
  964. if (len > MaxHeaderBytes)
  965. return false;
  966. var bytes = new byte[len];
  967. Buffer.BlockCopy(_headerBytes, 0, bytes, 0, _headerBytes.Length);
  968. Buffer.BlockCopy(headerBytes, 0, bytes, _headerBytes.Length, headerBytes.Length);
  969. _headerBytes = bytes;
  970. }
  971. else
  972. {
  973. _headerBytes = headerBytes;
  974. }
  975. // start parsing
  976. _startHeadersOffset = -1;
  977. _endHeadersOffset = -1;
  978. _headerByteStrings = new List<ByteString>();
  979. // find the end of headers
  980. var parser = new ByteParser(_headerBytes);
  981. for (; ; )
  982. {
  983. ByteString line = parser.ReadLine();
  984. if (line == null)
  985. {
  986. break;
  987. }
  988. if (_startHeadersOffset < 0)
  989. {
  990. _startHeadersOffset = parser.CurrentOffset;
  991. }
  992. if (line.IsEmpty)
  993. {
  994. _endHeadersOffset = parser.CurrentOffset;
  995. break;
  996. }
  997. _headerByteStrings.Add(line);
  998. }
  999. return true;
  1000. }
  1001. private static string UrlEncodeRedirect(string path)
  1002. {
  1003. // this method mimics the logic in HttpResponse.Redirect (which relies on internal methods)
  1004. // count non-ascii characters
  1005. byte[] bytes = Encoding.UTF8.GetBytes(path);
  1006. int count = bytes.Length;
  1007. int countNonAscii = 0;
  1008. for (int i = 0; i < count; i++)
  1009. {
  1010. if ((bytes[i] & 0x80) != 0)
  1011. {
  1012. countNonAscii++;
  1013. }
  1014. }
  1015. // encode all non-ascii characters using UTF-8 %XX
  1016. if (countNonAscii > 0)
  1017. {
  1018. // expand not 'safe' characters into %XX, spaces to +s
  1019. var expandedBytes = new byte[count + countNonAscii * 2];
  1020. int pos = 0;
  1021. for (int i = 0; i < count; i++)
  1022. {
  1023. byte b = bytes[i];
  1024. if ((b & 0x80) == 0)
  1025. {
  1026. expandedBytes[pos++] = b;
  1027. }
  1028. else
  1029. {
  1030. expandedBytes[pos++] = (byte)'%';
  1031. expandedBytes[pos++] = (byte)IntToHex[(b >> 4) & 0xf];
  1032. expandedBytes[pos++] = (byte)IntToHex[b & 0xf];
  1033. }
  1034. }
  1035. path = Encoding.ASCII.GetString(expandedBytes);
  1036. }
  1037. // encode spaces into %20
  1038. if (path.IndexOf(' ') >= 0)
  1039. {
  1040. path = path.Replace(" ", "%20");
  1041. }
  1042. return path;
  1043. }
  1044. private void ProcessPlugins()
  1045. {
  1046. if (_connection.Plugins != null)
  1047. {
  1048. foreach (string pluginTypeName in _connection.Plugins)
  1049. {
  1050. //AssemblyName assemblyName = new AssemblyName(pluginTypeName.Substring(pluginTypeName.IndexOf(",") + 1));
  1051. //Assembly.Load(assemblyName.Name + ".dll");
  1052. Type pluginType = Type.GetType(pluginTypeName);
  1053. object plugin = Activator.CreateInstance(pluginType);
  1054. var headersToAdd = (NameValueCollection)plugin.GetType().GetMethod("AddResponseHeaders").Invoke(plugin, null);
  1055. if (headersToAdd != null)
  1056. {
  1057. foreach (string name in headersToAdd)
  1058. {
  1059. SetResponseHeader(name, headersToAdd[name]);
  1060. }
  1061. }
  1062. }
  1063. }
  1064. }
  1065. #region Nested type: ByteParser
  1066. internal class ByteParser
  1067. {
  1068. private readonly byte[] _bytes;
  1069. private int _pos;
  1070. public ByteParser(byte[] bytes)
  1071. {
  1072. _bytes = bytes;
  1073. _pos = 0;
  1074. }
  1075. public int CurrentOffset
  1076. {
  1077. get { return _pos; }
  1078. }
  1079. public ByteString ReadLine()
  1080. {
  1081. ByteString line = null;
  1082. for (int i = _pos; i < _bytes.Length; i++)
  1083. {
  1084. if (_bytes[i] == (byte)'\n')
  1085. {
  1086. int len = i - _pos;
  1087. if (len > 0 && _bytes[i - 1] == (byte)'\r')
  1088. {
  1089. len--;
  1090. }
  1091. line = new ByteString(_bytes, _pos, len);
  1092. _pos = i + 1;
  1093. return line;
  1094. }
  1095. }
  1096. if (_pos < _bytes.Length)
  1097. {
  1098. line = new ByteString(_bytes, _pos, _bytes.Length - _pos);
  1099. }
  1100. _pos = _bytes.Length;
  1101. return line;
  1102. }
  1103. }
  1104. #endregion
  1105. #region Nested type: ByteString
  1106. internal class ByteString
  1107. {
  1108. private readonly byte[] _bytes;
  1109. private readonly int _length;
  1110. private readonly int _offset;
  1111. public ByteString(byte[] bytes, int offset, int length)
  1112. {
  1113. _bytes = bytes;
  1114. _offset = offset;
  1115. _length = length;
  1116. }
  1117. public byte[] Bytes
  1118. {
  1119. get { return _bytes; }
  1120. }
  1121. public bool IsEmpty
  1122. {
  1123. get { return (_bytes == null || _length == 0); }
  1124. }
  1125. public byte this[int index]
  1126. {
  1127. get { return _bytes[_offset + index]; }
  1128. }
  1129. public int Length
  1130. {
  1131. get { return _length; }
  1132. }
  1133. public int Offset
  1134. {
  1135. get { return _offset; }
  1136. }
  1137. public byte[] GetBytes()
  1138. {
  1139. var bytes = new byte[_length];
  1140. if (_length > 0) Buffer.BlockCopy(_bytes, _offset, bytes, 0, _length);
  1141. return bytes;
  1142. }
  1143. public string GetString(Encoding enc)
  1144. {
  1145. if (IsEmpty) return string.Empty;
  1146. return enc.GetString(_bytes, _offset, _length);
  1147. }
  1148. public string GetString()
  1149. {
  1150. return GetString(Encoding.UTF8);
  1151. }
  1152. public int IndexOf(char ch)
  1153. {
  1154. return IndexOf(ch, 0);
  1155. }
  1156. public int IndexOf(char ch, int offset)
  1157. {
  1158. for (int i = offset; i < _length; i++)
  1159. {
  1160. if (this[i] == (byte)ch) return i;
  1161. }
  1162. return -1;
  1163. }
  1164. public ByteString[] Split(char sep)
  1165. {
  1166. var list = new List<ByteString>();
  1167. int pos = 0;
  1168. while (pos < _length)
  1169. {
  1170. int i = IndexOf(sep, pos);
  1171. if (i < 0)
  1172. {
  1173. break;
  1174. }
  1175. list.Add(Substring(pos, i - pos));
  1176. pos = i + 1;
  1177. while (this[pos] == (byte)sep && pos < _length)
  1178. {
  1179. pos++;
  1180. }
  1181. }
  1182. if (pos < _length)
  1183. list.Add(Substring(pos));
  1184. return list.ToArray();
  1185. }
  1186. public ByteString Substring(int offset, int len)
  1187. {
  1188. return new ByteString(_bytes, _offset + offset, len);
  1189. }
  1190. public ByteString Substring(int offset)
  1191. {
  1192. return Substring(offset, _length - offset);
  1193. }
  1194. }
  1195. #endregion
  1196. }
  1197. }