SessionInProcHandler.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //
  2. // System.Web.SessionState.SessionInProcHandler
  3. //
  4. // Authors:
  5. // Marek Habersack <[email protected]>
  6. //
  7. // (C) 2006 Marek Habersack
  8. // (C) 2010 Novell, Inc (http://novell.com/)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.IO;
  32. using System.Collections;
  33. using System.Collections.Specialized;
  34. using System.Configuration.Provider;
  35. using System.Web.Caching;
  36. using System.Web.Configuration;
  37. using System.Threading;
  38. namespace System.Web.SessionState
  39. {
  40. internal sealed class InProcSessionItem
  41. {
  42. public bool locked;
  43. public bool cookieless;
  44. public ISessionStateItemCollection items;
  45. public DateTime lockedTime;
  46. public DateTime expiresAt;
  47. public ReaderWriterLockSlim rwlock;
  48. public Int32 lockId;
  49. public int timeout;
  50. public bool resettingTimeout;
  51. public HttpStaticObjectsCollection staticItems;
  52. internal InProcSessionItem ()
  53. {
  54. this.locked = false;
  55. this.cookieless = false;
  56. this.items = null;
  57. this.staticItems = null;
  58. this.lockedTime = DateTime.MinValue;
  59. this.expiresAt = DateTime.MinValue;
  60. this.rwlock = new ReaderWriterLockSlim ();
  61. this.lockId = Int32.MinValue;
  62. this.timeout = 0;
  63. this.resettingTimeout = false;
  64. }
  65. public void Dispose ()
  66. {
  67. if (rwlock != null) {
  68. rwlock.Dispose ();
  69. rwlock = null;
  70. }
  71. staticItems = null;
  72. if (items != null)
  73. items.Clear ();
  74. items = null;
  75. }
  76. ~InProcSessionItem ()
  77. {
  78. Dispose ();
  79. }
  80. }
  81. internal class SessionInProcHandler : SessionStateStoreProviderBase
  82. {
  83. const string CachePrefix = "@@@InProc@";
  84. const int CachePrefixLength = 10;
  85. const Int32 lockAcquireTimeout = 30000;
  86. CacheItemRemovedCallback removedCB;
  87. //NameValueCollection privateConfig;
  88. SessionStateItemExpireCallback expireCallback;
  89. HttpStaticObjectsCollection staticObjects;
  90. public override SessionStateStoreData CreateNewStoreData (HttpContext context, int timeout)
  91. {
  92. return new SessionStateStoreData (new SessionStateItemCollection (),
  93. staticObjects, timeout);
  94. }
  95. void InsertSessionItem (InProcSessionItem item, int timeout, string id)
  96. {
  97. if (item == null || String.IsNullOrEmpty (id))
  98. return;
  99. HttpRuntime.InternalCache.Insert (id,
  100. item,
  101. null,
  102. Cache.NoAbsoluteExpiration,
  103. TimeSpan.FromMinutes (timeout),
  104. CacheItemPriority.AboveNormal,
  105. removedCB);
  106. }
  107. void UpdateSessionItemTimeout (int timeout, string id)
  108. {
  109. if (String.IsNullOrEmpty (id))
  110. return;
  111. HttpRuntime.InternalCache.SetItemTimeout (id, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (timeout), true);
  112. }
  113. public override void CreateUninitializedItem (HttpContext context, string id, int timeout)
  114. {
  115. EnsureGoodId (id, true);
  116. InProcSessionItem item = new InProcSessionItem ();
  117. item.expiresAt = DateTime.UtcNow.AddMinutes (timeout);
  118. item.timeout = timeout;
  119. InsertSessionItem (item, timeout, CachePrefix + id);
  120. }
  121. public override void Dispose ()
  122. {
  123. }
  124. public override void EndRequest (HttpContext context)
  125. {
  126. if (staticObjects != null) {
  127. staticObjects.GetObjects ().Clear ();
  128. staticObjects = null;
  129. }
  130. }
  131. SessionStateStoreData GetItemInternal (HttpContext context,
  132. string id,
  133. out bool locked,
  134. out TimeSpan lockAge,
  135. out object lockId,
  136. out SessionStateActions actions,
  137. bool exclusive)
  138. {
  139. locked = false;
  140. lockAge = TimeSpan.MinValue;
  141. lockId = Int32.MinValue;
  142. actions = SessionStateActions.None;
  143. if (id == null)
  144. return null;
  145. Cache cache = HttpRuntime.InternalCache;
  146. string CacheId = CachePrefix + id;
  147. InProcSessionItem item = cache [CacheId] as InProcSessionItem;
  148. if (item == null)
  149. return null;
  150. bool readLocked = false, writeLocked = false;
  151. try {
  152. if (item.rwlock.TryEnterUpgradeableReadLock (lockAcquireTimeout))
  153. readLocked = true;
  154. else
  155. throw new ApplicationException ("Failed to acquire lock");
  156. if (item.locked) {
  157. locked = true;
  158. lockAge = DateTime.UtcNow.Subtract (item.lockedTime);
  159. lockId = item.lockId;
  160. return null;
  161. }
  162. if (exclusive) {
  163. if (item.rwlock.TryEnterWriteLock (lockAcquireTimeout))
  164. writeLocked = true;
  165. else
  166. throw new ApplicationException ("Failed to acquire lock");
  167. item.locked = true;
  168. item.lockedTime = DateTime.UtcNow;
  169. item.lockId++;
  170. lockId = item.lockId;
  171. }
  172. if (item.items == null) {
  173. actions = SessionStateActions.InitializeItem;
  174. item.items = new SessionStateItemCollection ();
  175. }
  176. if (item.staticItems == null)
  177. item.staticItems = staticObjects;
  178. return new SessionStateStoreData (item.items,
  179. item.staticItems,
  180. item.timeout);
  181. } catch {
  182. // we want such errors to be passed to the application.
  183. throw;
  184. } finally {
  185. if (writeLocked)
  186. item.rwlock.ExitWriteLock ();
  187. if (readLocked)
  188. item.rwlock.ExitUpgradeableReadLock ();
  189. }
  190. }
  191. public override SessionStateStoreData GetItem (HttpContext context,
  192. string id,
  193. out bool locked,
  194. out TimeSpan lockAge,
  195. out object lockId,
  196. out SessionStateActions actions)
  197. {
  198. EnsureGoodId (id, false);
  199. return GetItemInternal (context, id, out locked, out lockAge, out lockId, out actions, false);
  200. }
  201. public override SessionStateStoreData GetItemExclusive (HttpContext context,
  202. string id,
  203. out bool locked,
  204. out TimeSpan lockAge,
  205. out object lockId,
  206. out SessionStateActions actions)
  207. {
  208. EnsureGoodId (id, false);
  209. return GetItemInternal (context, id, out locked, out lockAge, out lockId, out actions, true);
  210. }
  211. public override void Initialize (string name, NameValueCollection config)
  212. {
  213. if (String.IsNullOrEmpty (name))
  214. name = "Session InProc handler";
  215. removedCB = new CacheItemRemovedCallback (OnSessionRemoved);
  216. //privateConfig = config;
  217. base.Initialize (name, config);
  218. }
  219. public override void InitializeRequest (HttpContext context)
  220. {
  221. staticObjects = HttpApplicationFactory.ApplicationState.SessionObjects.Clone ();
  222. }
  223. public override void ReleaseItemExclusive (HttpContext context,
  224. string id,
  225. object lockId)
  226. {
  227. EnsureGoodId (id, true);
  228. string CacheId = CachePrefix + id;
  229. InProcSessionItem item = HttpRuntime.InternalCache [CacheId] as InProcSessionItem;
  230. if (item == null || lockId == null || lockId.GetType() != typeof(Int32) || item.lockId != (Int32)lockId)
  231. return;
  232. bool locked = false;
  233. ReaderWriterLockSlim itemLock = null;
  234. try {
  235. itemLock = item.rwlock;
  236. if (itemLock != null && itemLock.TryEnterWriteLock (lockAcquireTimeout))
  237. locked = true;
  238. else
  239. throw new ApplicationException ("Failed to acquire lock");
  240. item.locked = false;
  241. } catch {
  242. throw;
  243. } finally {
  244. if (locked && itemLock != null)
  245. itemLock.ExitWriteLock ();
  246. }
  247. }
  248. public override void RemoveItem (HttpContext context,
  249. string id,
  250. object lockId,
  251. SessionStateStoreData item)
  252. {
  253. EnsureGoodId (id, true);
  254. string CacheId = CachePrefix + id;
  255. Cache cache = HttpRuntime.InternalCache;
  256. InProcSessionItem inProcItem = cache [CacheId] as InProcSessionItem;
  257. if (inProcItem == null || lockId == null || lockId.GetType() != typeof(Int32) || inProcItem.lockId != (Int32)lockId)
  258. return;
  259. bool locked = false;
  260. ReaderWriterLockSlim itemLock = null;
  261. try {
  262. itemLock = inProcItem.rwlock;
  263. if (itemLock != null && itemLock.TryEnterWriteLock (lockAcquireTimeout))
  264. locked = true;
  265. else
  266. throw new ApplicationException ("Failed to acquire lock after");
  267. cache.Remove (CacheId);
  268. } catch {
  269. throw;
  270. } finally {
  271. if (locked)
  272. itemLock.ExitWriteLock ();
  273. }
  274. }
  275. public override void ResetItemTimeout (HttpContext context, string id)
  276. {
  277. EnsureGoodId (id, true);
  278. string CacheId = CachePrefix + id;
  279. Cache cache = HttpRuntime.InternalCache;
  280. InProcSessionItem item = cache [CacheId] as InProcSessionItem;
  281. if (item == null)
  282. return;
  283. bool locked = false;
  284. ReaderWriterLockSlim itemLock = null;
  285. try {
  286. itemLock = item.rwlock;
  287. if (itemLock != null && itemLock.TryEnterWriteLock (lockAcquireTimeout))
  288. locked = true;
  289. else
  290. throw new ApplicationException ("Failed to acquire lock after");
  291. item.resettingTimeout = true;
  292. UpdateSessionItemTimeout (item.timeout, CacheId);
  293. } catch {
  294. throw;
  295. } finally {
  296. if (locked && itemLock != null)
  297. itemLock.ExitWriteLock ();
  298. }
  299. }
  300. /* In certain situations the 'item' parameter passed to SetAndReleaseItemExclusive
  301. may be null. The issue was reported in bug #333898, but the reporter cannot
  302. provide a test case that triggers the issue. Added work around the problem
  303. in the way that should have the least impact on the rest of the code. If 'item'
  304. is null, then the new session item is created without the items and staticItems
  305. collections - they will be initialized to defaults when retrieving the session
  306. item. This is not a correct fix, but since there is no test case this is the best
  307. what can be done right now.
  308. */
  309. public override void SetAndReleaseItemExclusive (HttpContext context,
  310. string id,
  311. SessionStateStoreData item,
  312. object lockId,
  313. bool newItem)
  314. {
  315. EnsureGoodId (id, true);
  316. string CacheId = CachePrefix + id;
  317. Cache cache = HttpRuntime.InternalCache;
  318. InProcSessionItem inProcItem = cache [CacheId] as InProcSessionItem;
  319. ISessionStateItemCollection itemItems = null;
  320. int itemTimeout = 20;
  321. HttpStaticObjectsCollection itemStaticItems = null;
  322. if (item != null) {
  323. itemItems = item.Items;
  324. itemTimeout = item.Timeout;
  325. itemStaticItems = item.StaticObjects;
  326. }
  327. if (newItem || inProcItem == null) {
  328. inProcItem = new InProcSessionItem ();
  329. inProcItem.timeout = itemTimeout;
  330. inProcItem.expiresAt = DateTime.UtcNow.AddMinutes (itemTimeout);
  331. if (lockId.GetType() == typeof(Int32))
  332. inProcItem.lockId = (Int32)lockId;
  333. } else {
  334. if (lockId == null || lockId.GetType() != typeof(Int32) || inProcItem.lockId != (Int32)lockId)
  335. return;
  336. inProcItem.resettingTimeout = true;
  337. cache.Remove (CacheId);
  338. }
  339. bool locked = false;
  340. ReaderWriterLockSlim itemLock = null;
  341. try {
  342. itemLock = inProcItem.rwlock;
  343. if (itemLock != null && itemLock.TryEnterWriteLock (lockAcquireTimeout))
  344. locked = true;
  345. else if (itemLock != null)
  346. throw new ApplicationException ("Failed to acquire lock");
  347. if (inProcItem.resettingTimeout)
  348. UpdateSessionItemTimeout (itemTimeout, CacheId);
  349. else {
  350. inProcItem.locked = false;
  351. inProcItem.items = itemItems;
  352. inProcItem.staticItems = itemStaticItems;
  353. InsertSessionItem (inProcItem, itemTimeout, CacheId);
  354. }
  355. } catch {
  356. throw;
  357. } finally {
  358. if (locked && itemLock != null)
  359. itemLock.ExitWriteLock ();
  360. }
  361. }
  362. public override bool SetItemExpireCallback (SessionStateItemExpireCallback expireCallback)
  363. {
  364. this.expireCallback = expireCallback;
  365. return true;
  366. }
  367. void EnsureGoodId (string id, bool throwOnNull)
  368. {
  369. if (id == null)
  370. if (throwOnNull)
  371. throw new HttpException ("Session ID is invalid");
  372. else
  373. return;
  374. if (id.Length > SessionIDManager.SessionIDMaxLength)
  375. throw new HttpException ("Session ID too long");
  376. }
  377. void OnSessionRemoved (string key, object value, CacheItemRemovedReason reason)
  378. {
  379. if (expireCallback != null) {
  380. if (key.StartsWith (CachePrefix, StringComparison.OrdinalIgnoreCase))
  381. key = key.Substring (CachePrefixLength);
  382. if (value is SessionStateStoreData)
  383. expireCallback (key, (SessionStateStoreData)value);
  384. else if (value is InProcSessionItem) {
  385. InProcSessionItem item = (InProcSessionItem)value;
  386. if (item.resettingTimeout) {
  387. item.resettingTimeout = false;
  388. return;
  389. }
  390. expireCallback (key,
  391. new SessionStateStoreData (
  392. item.items,
  393. item.staticItems,
  394. item.timeout));
  395. item.Dispose ();
  396. } else
  397. expireCallback (key, null);
  398. } else if (value is InProcSessionItem) {
  399. InProcSessionItem item = (InProcSessionItem)value;
  400. if (item.resettingTimeout) {
  401. item.resettingTimeout = false;
  402. return;
  403. }
  404. item.Dispose ();
  405. }
  406. }
  407. }
  408. }