-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBootstrapper.cs
1022 lines (856 loc) · 39 KB
/
Bootstrapper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Copyright (c) 2010 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region Assembly Information
using System.Reflection;
using System.Runtime.InteropServices;
using System.Web;
using Elmah.Bootstrapper;
[assembly: AssemblyTitle("Elmah.Bootstrapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ELMAH")]
[assembly: AssemblyCopyright("Copyright \u00a9 2010 Atif Aziz. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.21423.0")]
[assembly: AssemblyFileVersion("1.0.21423.735")]
#if DEBUG
[assembly: AssemblyConfiguration("DEBUG")]
#else
[assembly: AssemblyConfiguration("RELEASE")]
#endif
#endregion
[assembly: PreApplicationStartMethod(typeof(Ignition), "Start")]
namespace Elmah.Bootstrapper
{
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Design;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
using System.Xml;
using Assertions;
#endregion
public static class ErrorLogWeb
{
public static class UrlPathInfoTokener
{
static Func<string, int> _current;
static Func<string, int> _default;
public static Func<string, int> Current
{
get => _current ?? Default;
set => _current = value ?? throw new ArgumentNullException(nameof(value));
}
public static Func<string, int> Default => _default ?? (_default = CreateDefault());
static Func<string, int> CreateDefault()
{
return Create(Configuration.Default.GetSetting("web:path")?.Split()
?? new[] { "elmah", "errors", "errorlog" });
}
public static readonly char[] Slash = { '/' };
public static Func<string, int> Create(params string[] paths)
{
var q = from s in paths
select s.TrimStart(Slash).TrimEnd(Slash) into s
where s.Length > 0
select "/" + s;
paths = q.ToArray();
if (paths.Length == 0)
return delegate { return -1; };
return path =>
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (path.Length == 0 || path[0] != '/') throw new ArgumentException(null, nameof(path));
var match = paths.FirstOrDefault(p => path.StartsWith(p, StringComparison.Ordinal));
return match == null ? -1
: path.Length == match.Length ? path.Length
: path[match.Length] == '/' ? match.Length
: -1;
};
}
}
}
sealed class ErrorLogHandlerMappingModule : HttpModuleBase
{
ErrorLogPageFactory _errorLogPageFactory;
ErrorLogPageFactory HandlerFactory => _errorLogPageFactory ?? (_errorLogPageFactory = new ErrorLogPageFactory());
protected override void OnInit(HttpApplication application)
{
application.Subscribe(h => application.PostMapRequestHandler += h, OnPostMapRequestHandler);
application.Subscribe(h => application.EndRequest += h, OnEndRequest);
}
void OnPostMapRequestHandler(HttpContextBase context)
{
var request = context.Request;
var filePath = request.FilePath;
// The parser returns the index to the start of the URL path
// info. Everything to the left of it is the script path.
// If the index is exactly the length of the string then
// the file path identifies the script path entirely and
// path info is empty.
var pathInfoIndex = ErrorLogWeb.UrlPathInfoTokener.Current(filePath);
if (pathInfoIndex < 0 || pathInfoIndex > filePath.Length
|| (pathInfoIndex < filePath.Length && filePath[pathInfoIndex] != '/'))
{
// URL is a mismatch if index is one of the following:
// - Less than 0 meaning nothing found.
// - Character at index is not a forward slash (/).
// - Index is invalid because it is out of range;
// identifies an implementation issue with the parser.
return;
}
var url = filePath.Substring(0, pathInfoIndex);
// ReSharper disable once PossibleNullReferenceException
var queryString = request.Url.Query;
var pathInfo = pathInfoIndex == filePath.Length
? string.Empty
: filePath.Substring(pathInfoIndex);
context.RewritePath(url, pathInfo,
queryString.Length > 0 && queryString[0] == '?'
? queryString.Substring(1)
: queryString);
var pathTranslated = request.PhysicalApplicationPath;
var factory = HandlerFactory;
var handler = factory.GetHandler(context, request.HttpMethod, url, pathTranslated);
if (handler == null)
return;
context.Items[this] = new ContextState
{
Handler = handler,
HandlerFactory = factory,
};
context.Handler = handler;
}
void OnEndRequest(HttpContextBase context)
{
var state = context.Items[this] as ContextState;
state?.HandlerFactory.ReleaseHandler(state.Handler);
}
sealed class ContextState
{
public IHttpHandler Handler;
public IHttpHandlerFactory HandlerFactory;
}
}
public static class Ignition
{
static readonly object Lock = new object();
static bool _registered;
public static void Start()
{
lock (Lock)
{
if (_registered)
return;
StartImpl();
_registered = true;
}
}
static void StartImpl()
{
// TODO Consider what happens if registration fails halfway
ServiceCenter.Current = GetServiceProvider;
foreach (var type in DefaultModuleTypeSet)
HttpApplication.RegisterModule(type);
}
static IEnumerable<Type> DefaultModuleTypeSet
{
get
{
yield return typeof(ErrorLogSecurityModule);
yield return typeof(ErrorLogModule);
yield return typeof(ErrorMailModule);
yield return typeof(ErrorFilterModule);
yield return typeof(ErrorTweetModule);
yield return typeof(ErrorLogHandlerMappingModule);
yield return typeof(InitializationModule);
}
}
public static IServiceProvider GetServiceProvider(object context) =>
GetServiceProvider(AsHttpContextBase(context));
static HttpContextBase AsHttpContextBase(object context)
=> context is HttpContextBase hcb ? hcb
: context is HttpContext hc ? new HttpContextWrapper(hc)
: null;
static readonly object ContextKey = new object();
static IServiceProvider GetServiceProvider(HttpContextBase context)
{
if (context?.Items[ContextKey] is IServiceProvider sp)
return sp;
var container = new ServiceContainer(ServiceCenter.Default(context));
if (context != null)
{
var cachedErrorLog = new ErrorLog[1];
container.AddService(typeof (ErrorLog), delegate
{
return cachedErrorLog[0] ?? (cachedErrorLog[0] = ErrorLogFactory());
});
context.Items[ContextKey] = container;
}
return container;
}
static Func<ErrorLog> _errorLogFactory;
static Func<ErrorLog> ErrorLogFactory => _errorLogFactory ?? (_errorLogFactory = CreateErrorLogFactory());
static Func<ErrorLog> CreateErrorLogFactory()
{
string xmlLogPath;
return ShouldUseErrorLog(config => new SqlErrorLog(config))
?? ShouldUseErrorLog(config => new SQLiteErrorLog(config))
?? ShouldUseErrorLog(config => new SqlServerCompactErrorLog(config))
?? ShouldUseErrorLog(config => new OracleErrorLog(config))
?? ShouldUseErrorLog(config => new MySqlErrorLog(config))
?? ShouldUseErrorLog(config => new PgsqlErrorLog(config))
// ReSharper disable once AssignNullToNotNullAttribute
?? (Directory.Exists(xmlLogPath = HostingEnvironment.MapPath("~/App_Data/errors/xmlstore"))
? (() => new XmlFileErrorLog(xmlLogPath))
: new Func<ErrorLog>(() => new MemoryErrorLog
{
ApplicationName =
!string.IsNullOrWhiteSpace(ApplicationName)
? ApplicationName
: AppDomain.CurrentDomain.FriendlyName
}));
}
static Func<ErrorLog> ShouldUseErrorLog<T>(Func<IDictionary, T> factory) where T : ErrorLog
{
var logTypeName = typeof(T).Name;
const string errorlogSuffix = nameof(ErrorLog);
if (logTypeName.EndsWith(errorlogSuffix, StringComparison.OrdinalIgnoreCase))
logTypeName = logTypeName.Substring(0, logTypeName.Length - errorlogSuffix.Length);
var csName = "elmah:" + logTypeName;
var css = ConfigurationManager.ConnectionStrings[csName];
if (string.IsNullOrEmpty(css?.ConnectionString))
return null;
var config = new Hashtable
{
{ "connectionString", css.ConnectionString}
};
foreach (var e in Configuration.Default.GetSettings(logTypeName))
config[e.Key] = e.Value;
return () =>
{
ErrorLog log = factory(/* copy */ new Hashtable(config));
if (string.IsNullOrEmpty(log.ApplicationName))
log.ApplicationName = ApplicationName;
return log;
};
}
static string _applicationName;
static string ApplicationName => _applicationName ?? (_applicationName = Configuration.Default.GetSetting("applicationName"));
}
sealed class Configuration
{
readonly NameValueCollection _settings;
public static readonly Configuration Default = new Configuration(ConfigurationManager.AppSettings);
Configuration(NameValueCollection settings) { _settings = settings; }
public string GetSetting(string key) { return _settings["elmah:" + key]; }
public IEnumerable<KeyValuePair<string, string>> GetSettings(string scope)
{
var prefix = "elmah:" + scope + ":";
return
from key in _settings.AllKeys
where key.Length > prefix.Length
&& key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
select new KeyValuePair<string, string>(key.Substring(prefix.Length), _settings[key]);
}
}
public class HttpModuleInitializingEventArgs : EventArgs
{
List<IDisposable> _disposables;
public IHttpModule Module { get; }
public HttpApplication Application { get; }
public bool HasDisposables => _disposables?.Count > 0;
public IEnumerable<IDisposable> Disposables => HasDisposables
? _disposables.AsEnumerable()
: Enumerable.Empty<IDisposable>();
public HttpModuleInitializingEventArgs(IHttpModule module, HttpApplication application)
{
Module = module ?? throw new ArgumentNullException(nameof(module));
Application = application ?? throw new ArgumentNullException(nameof(application));
}
public void OnDispose(IDisposable disposable)
{
if (disposable == null) throw new ArgumentNullException(nameof(disposable));
(_disposables ?? (_disposables = new List<IDisposable>())).Add(disposable);
}
public void OnDispose(Action action) => OnDispose(new DelegatingDisposable(action));
}
sealed class DelegatingDisposable : IDisposable
{
Action OnDispose { get; }
public DelegatingDisposable(Action onDispose) { OnDispose = onDispose; }
public void Dispose() => OnDispose?.Invoke();
}
public static class HttpModuleInitialization
{
public static event EventHandler<HttpModuleInitializingEventArgs> Initializing;
internal static void OnInitializing(HttpModuleInitializingEventArgs args) { Initializing?.Invoke(args.Module, args); }
}
public static class App
{
public static void OnModuleEvent<T, THandler, TEventArgs>(
Action<T, THandler> subscriber,
Action<T, THandler> unsubcriber,
Func<Action<object, TEventArgs>, THandler> converter,
Action<T, TEventArgs> handler)
{
if (subscriber == null) throw new ArgumentNullException(nameof(subscriber));
if (unsubcriber == null) throw new ArgumentNullException(nameof(unsubcriber));
if (converter == null) throw new ArgumentNullException(nameof(converter));
if (handler == null) throw new ArgumentNullException(nameof(handler));
HttpModuleInitialization.Initializing += (_, args) =>
{
var mhs =
from module in args.Application.Modules.AsEnumerable().Select(e => e.Value).OfType<T>()
select new
{
Module = module,
Handler = converter((sender, a) => handler((T) sender, a)),
};
foreach (var mh in mhs)
{
subscriber(mh.Module, mh.Handler);
args.OnDispose(() => unsubcriber(mh.Module, mh.Handler));
}
};
}
public static void OnError(Action<Exception> handler) => OnErrorImpl(handler);
public static void OnError(Action<HttpContextBase> handler) => OnErrorImpl(handler2: handler);
public static void OnError(Action<Exception, HttpContextBase> handler) => OnErrorImpl(handler3: handler);
static void OnErrorImpl(Action<Exception> handler1 = null,
Action<HttpContextBase> handler2 = null,
Action<Exception, HttpContextBase> handler3 = null)
{
HttpModuleInitialization.Initializing += (_, args) =>
{
args.Application.Error += (sender, __) =>
{
var app = (HttpApplication)sender;
handler1?.Invoke(app.Server.GetLastError());
handler2?.Invoke(new HttpContextWrapper(app.Context));
handler3?.Invoke(app.Server.GetLastError(), new HttpContextWrapper(app.Context));
};
};
}
}
/* e.g.
static class WebApp
{
static void Init()
{
App.OnModuleEvent(
(m, h) => m.Filtering += h,
(m, h) => m.Filtering -= h,
h => new ExceptionFilterEventHandler((sender, args) => h(sender, args)),
(IExceptionFiltering sender, ExceptionFilterEventArgs args) =>
{
// TODO event handling code
});
App.OnModuleEvent(
(m, h) => m.Mailing += h,
(m, h) => m.Mailing -= h,
h => new ErrorMailEventHandler((sender, args) => h(sender, args)),
(Elmah.ErrorMailModule sender, ErrorMailEventArgs args) =>
{
// TODO event handling code
});
App.OnModuleEvent(
(m, h) => m.Mailing += h,
(m, h) => m.Mailing -= h,
h => new ErrorMailEventHandler((sender, args) => h(sender, args)),
(Elmah.ErrorMailModule sender, ErrorMailEventArgs args) =>
{
// TODO event handling code
});
App.OnModuleEvent(
(m, h) => m.DisposingMail += h,
(m, h) => m.DisposingMail -= h,
h => new ErrorMailEventHandler((sender, args) => h(sender, args)),
(Elmah.ErrorMailModule sender, ErrorMailEventArgs args) =>
{
// TODO event handling code
});
App.OnModuleEvent(
(m, h) => m.Logged += h,
(m, h) => m.Logged -= h,
h => new ErrorLoggedEventHandler((sender, args) => h(sender, args)),
(Elmah.ErrorLogModule sender, ErrorLoggedEventArgs args) =>
{
// TODO event handling code
});
}
}
*/
sealed class InitializationModule : IHttpModule
{
IDisposable[] _disposables;
public void Init(HttpApplication context)
{
var args = new HttpModuleInitializingEventArgs(this, context);
HttpModuleInitialization.OnInitializing(args);
if (args.HasDisposables)
_disposables = args.Disposables.ToArray();
}
public void Dispose()
{
if ((_disposables?.Length ?? 0) == 0)
return;
// ReSharper disable once PossibleNullReferenceException
var disposables = new IDisposable[_disposables.Length];
_disposables?.CopyTo(disposables, 0);
_disposables = null;
foreach (var disposable in disposables)
try { disposable?.Dispose(); } catch { /* ignored */ }
}
}
public static class LoggedException
{
static readonly ConditionalWeakTable<Exception, ErrorLogEntry> Table = new ConditionalWeakTable<Exception, ErrorLogEntry>();
internal static void Add(ErrorLogEntry entry)
{
if (entry == null) throw new ArgumentNullException(nameof(entry));
if (entry.Error.Exception == null) throw new ArgumentException(null, nameof(entry));
Table.Add(entry.Error.Exception, entry);
}
public static ErrorLogEntry RecallErrorLogEntry(Exception exception) =>
exception == null
? throw new ArgumentNullException(nameof(exception))
: (Table.TryGetValue(exception, out var entry) ? entry : null);
}
sealed class ErrorLogModule : Elmah.ErrorLogModule
{
protected override void OnLogged(ErrorLoggedEventArgs args)
{
LoggedException.Add(args.Entry);
base.OnLogged(args);
}
}
public static class ErrorTextFormatterFactory
{
public static Func<ErrorTextFormatter> Default => () => new ErrorMailHtmlFormatter();
static Func<ErrorTextFormatter> _current;
public static Func<ErrorTextFormatter> Current
{
get => _current ?? Default;
set => _current = value ?? throw new ArgumentNullException(nameof(value));
}
}
public class MailMessageTag
{
public bool ShouldNotSend { get; set; }
public ErrorMailModuleSmtpConfiguration ErrorMailModuleSmtpConfiguration { get; set; }
}
public class ErrorMailModuleSmtpConfiguration
{
public string Host { get; }
public int Port { get; }
public NetworkCredential Credential { get; }
public bool UseSsl { get; }
public ErrorMailModuleSmtpConfiguration(string host, int port) :
this(host, port, null) {}
public ErrorMailModuleSmtpConfiguration(string host, int port, NetworkCredential credential) :
this(host, port, credential, false) {}
public ErrorMailModuleSmtpConfiguration(string host, int port, NetworkCredential credential, bool useSsl)
{
Host = host ?? string.Empty;
Port = port;
Credential = credential;
UseSsl = useSsl;
}
}
public static class MailMessageTagLink
{
static readonly ConditionalWeakTable<MailMessage, MailMessageTag> Tags = new ConditionalWeakTable<MailMessage, MailMessageTag>();
public static MailMessageTag GetTag(this MailMessage mail) => Tags.GetOrCreateValue(mail);
}
sealed class ErrorMailModule : Elmah.ErrorMailModule
{
protected override ErrorTextFormatter CreateErrorFormatter() =>
ErrorTextFormatterFactory.Current() ?? base.CreateErrorFormatter();
protected override object GetConfig()
{
var config = new Hashtable();
foreach (var e in Configuration.Default.GetSettings("errorMail"))
config[e.Key] = e.Value;
if (Recipients.To.Count > 0)
config["to"] = Recipients.To.ToString();
return config.Count == 0 ? null : config;
}
protected override void OnMailing(ErrorMailEventArgs args)
{
var mail = args.Mail;
var recipients = Recipients;
if (recipients != null)
{
mail.To.AddRange(recipients.To);
mail.CC.AddRange(recipients.Cc);
mail.Bcc.AddRange(recipients.Bcc);
}
var userName = AuthUserName;
var password = AuthPassword;
var credential = !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)
? new NetworkCredential(userName, password)
: null;
mail.GetTag().ErrorMailModuleSmtpConfiguration = new ErrorMailModuleSmtpConfiguration(
SmtpServer, SmtpPort,
credential, UseSsl);
base.OnMailing(args);
}
protected override void OnMailed(ErrorMailEventArgs args)
{
if (args.Mail.GetTag().ShouldNotSend)
return;
base.OnMailed(args);
}
protected override void SendMail(MailMessage mail)
{
if (mail.GetTag().ShouldNotSend)
return;
base.SendMail(mail);
}
static IDisposable _configRefreshSubscription;
static RecipientsCollection _recipients;
static RecipientsCollection Recipients => _recipients ?? (_recipients = Load(() => _recipients = null));
static RecipientsCollection Load(Action onInvalidation)
{
if (_configRefreshSubscription == null)
{
var subscription = ErrorMailConfig.AddRefreshedListener(delegate { onInvalidation(); });
if (!ReferenceEquals(null, Interlocked.CompareExchange(ref _configRefreshSubscription, subscription, null)))
subscription.Dispose();
}
var recipients = new RecipientsCollection();
var entries =
from e in ErrorMailConfig.Entries.Where(e => e.Key == ":to"
|| e.Key == ":cc"
|| e.Key == ":bcc")
let id = e.Key[1]
select new
{
Collection = id == 't' ? recipients.To
: id == 'c' ? recipients.Cc
: recipients.Bcc,
Addresses = e.Value,
};
foreach (var e in entries)
e.Collection.Add(e.Addresses);
return recipients;
}
sealed class RecipientsCollection
{
public readonly MailAddressCollection To = new MailAddressCollection();
public readonly MailAddressCollection Cc = new MailAddressCollection();
public readonly MailAddressCollection Bcc = new MailAddressCollection();
}
}
public static class ErrorMailConfig
{
static readonly string CacheKey = typeof(ErrorMailConfig).FullName + ":mail";
static IEnumerable<KeyValuePair<string, string>> _entries;
public static IEnumerable<KeyValuePair<string, string>> Entries =>
_entries ?? (_entries = Load(() => { _entries = null; Refreshed?.Invoke(null, EventArgs.Empty); }));
static IEnumerable<KeyValuePair<string, string>> Load(Action onInvalidation)
{
const string configPath = "~/Elmah.ErrorMail.config";
var vpp = HostingEnvironment.VirtualPathProvider;
var entries = vpp.FileExists(configPath)
? from g in Gini.Ini.Parse(vpp.GetFile(configPath).ReadAllText())
from e in g
select KeyValuePair.Create(g.Key + ":" + e.Key, e.Value)
: Enumerable.Empty<KeyValuePair<string, string>>();
HttpRuntime.Cache.Insert(CacheKey, CacheKey,
vpp.GetCacheDependency(configPath, new[] { configPath }, DateTime.Now),
delegate { onInvalidation(); });
return entries;
}
public static event EventHandler Refreshed;
public static IDisposable AddRefreshedListener(EventHandler handler)
{
if (handler == null) throw new ArgumentNullException(nameof(handler));
Refreshed += handler;
return new DelegatingDisposable(() => Refreshed -= handler);
}
}
sealed class ErrorLogSecurityModule : HttpModuleBase, IRequestAuthorizationHandler
{
static readonly string CacheKey = typeof(ErrorLogSecurityModule).FullName + ":predicate";
static Predicate<HttpContextBase> _authority;
public bool Authorize(HttpContext context)
{
return Authority(new HttpContextWrapper(context));
}
static Predicate<HttpContextBase> Authority =>
_authority ?? (_authority = Load(() => _authority = null));
static Predicate<HttpContextBase> Load(Action onInvalidation)
{
const string configPath = "~/Elmah.Athz.config";
var vpp = HostingEnvironment.VirtualPathProvider;
var entries =
from path in new[] { configPath }
where vpp.FileExists(path)
from line in vpp.GetFile(configPath).ReadLines()
select line.Trim()
into line
where line.Length > 0 && line[0] != '#'
select Regex.Match(line, @"
^
(?<not>!?) # not
( (?<role> \^) (?<name>\w[\w\p{P}\d]*) # role (^) + name
| (?<name> [*?] | \w[\w\p{P}\d]* ) # authenticated (*) | anonymous (?) | username
| (?<name> @local) # special
)
(?:\s*\#.*)? # comment
$", RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace)
into m
where m.Success
select m.Groups into gs
select new
{
Denial = gs["not" ].Length > 0,
IsRole = gs["role"].Success,
Name = gs["name"].Value,
};
var acl = entries.ToLookup(e => e.Denial,
e => e.IsRole
? Predicates.IsInRole(e.Name)
: "*" == e.Name
? Predicates.IsAuthenticated
: "?" == e.Name
? Predicates.IsAnonymous
: "@local".Equals(e.Name, StringComparison.OrdinalIgnoreCase)
? Predicates.IsLocalRequest
: Predicates.IsId(e.Name));
var denials = acl[true ].ToArray();
var grants = acl[false].ToArray();
bool Predicate(HttpContextBase principal) =>
!denials.Any(p => p(principal)) && grants.Any(p => p(principal));
HttpRuntime.Cache.Insert(CacheKey, CacheKey,
vpp.GetCacheDependency(configPath, new[] { configPath }, DateTime.Now),
delegate { onInvalidation(); });
return Predicate;
}
static class Predicates
{
public static readonly Predicate<HttpContextBase> IsAuthenticated = ctx => ctx.User.Identity.IsAuthenticated;
public static readonly Predicate<HttpContextBase> IsAnonymous = ctx => !IsAuthenticated(ctx);
public static readonly Predicate<HttpContextBase> IsLocalRequest = ctx => ctx.Request.IsLocal;
public static Predicate<HttpContextBase> IsId(string name) => ctx => name.Equals(ctx.User.Identity.Name, StringComparison.OrdinalIgnoreCase);
public static Predicate<HttpContextBase> IsInRole(string name) => ctx => ctx.User.IsInRole(name);
}
}
sealed class ErrorFilterModule : Elmah.ErrorFilterModule
{
static readonly string CacheKey = typeof(ErrorFilterModule).FullName + ":assertion";
static IAssertion _assertion;
public override void Init(HttpApplication application)
{
var modules =
from ms in new[]
{
from m in application.Modules.AsEnumerable()
select m.Value
}
from m in ms.OfType<IExceptionFiltering>()
select m;
foreach (var filtering in modules)
filtering.Filtering += OnErrorModuleFiltering;
}
public override IAssertion Assertion =>
_assertion ?? (_assertion = LoadAssertion(() => _assertion = null) ?? base.Assertion);
static readonly DelegatingAssertion FalseAssertion = new DelegatingAssertion(_ => false);
static IAssertion LoadAssertion(Action onInvalidation)
{
var configPath = (ConfigurationManager.AppSettings["elmah:errorFilter:assertion"] ?? string.Empty).Trim();
if (configPath.Length == 0)
configPath = "~/Elmah.ErrorFilter.config";
var vpp = HostingEnvironment.VirtualPathProvider;
var assertion = TryLoadAssertion(() => vpp.TryOpen(configPath)) ?? FalseAssertion;
HttpRuntime.Cache.Insert(CacheKey, assertion,
vpp.GetCacheDependency(configPath, new[] { configPath }, DateTime.Now),
delegate { onInvalidation(); });
return assertion;
}
static IAssertion TryLoadAssertion(Func<Stream> opener)
{
using (var stream = opener() ?? Stream.Null)
using (var reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
var trimmed = content.Trim();
if (trimmed.Length == 0)
return null;
XmlElement element;
if (trimmed[0] == '<') // Assume XML
{
var config = new XmlDocument();
config.LoadXml(content);
element = (XmlElement) config.SelectSingleNode("errorFilter/test/*")
?? (XmlElement) config.SelectSingleNode("test/*")
?? config.DocumentElement;
}
else // Assume JScript expression
{
var config = new XmlDocument();
var expression = config.CreateElement("expression");
expression.AppendChild(config.CreateTextNode(content));
var jscript = config.CreateElement("jscript");
jscript.AppendChild(expression);
config.AppendChild(jscript);
element = config.DocumentElement;
}
return AssertionFactory.Create(element);
}
}
sealed class DelegatingAssertion : IAssertion
{
readonly Predicate<object> _predicate;
public DelegatingAssertion(Predicate<object> predicate) { _predicate = predicate; }
public bool Test(object context) { return _predicate(context); }
}
}
static class KeyValuePair
{
public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value) => new KeyValuePair<TKey,TValue>(key, value);
}
static class WebExtensions
{
/// <summary>
/// Helps with subscribing to <see cref="HttpApplication"/> events
/// but where the handler
/// </summary>
public static void Subscribe(this HttpApplication application,
Action<EventHandler> subscriber,
Action<HttpContextBase> handler)
{
if (application == null) throw new ArgumentNullException(nameof(application));
if (subscriber == null) throw new ArgumentNullException(nameof(subscriber));
if (handler == null) throw new ArgumentNullException(nameof(handler));
subscriber((sender, _) => handler(new HttpContextWrapper(((HttpApplication)sender).Context)));
}
/// <summary>
/// Same as <see cref="IHttpHandlerFactory.GetHandler"/> except the
/// HTTP context is typed as <see cref="HttpContextBase"/> instead
/// of <see cref="HttpContext"/>.
/// </summary>
public static IHttpHandler GetHandler(this IHttpHandlerFactory factory,
HttpContextBase context, string requestType,
string url, string pathTranslated)
{
if (factory == null) throw new ArgumentNullException(nameof(factory));
return factory.GetHandler(context.ApplicationInstance.Context, requestType, url, pathTranslated);
}
}
static class HttpModuleCollectionExtensions
{
public static IEnumerable<KeyValuePair<string, IHttpModule>> AsEnumerable(this HttpModuleCollection modules)
{
if (modules == null) throw new ArgumentNullException(nameof(modules));
return from m in Enumerable.Range(0, modules.Count)
select KeyValuePair.Create(modules.GetKey(m), modules[m]);
}
}
static class CacheExtensions
{
public static void Insert(this Cache cache, string key, object value, CacheDependency cacheDependency, CacheItemRemovedCallback onRemovedCallback)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
cache.Insert(key, value, cacheDependency,
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default, onRemovedCallback);
}
}
static class VirtualPathProviderExtensions
{
public static Stream TryOpen(this VirtualPathProvider vpp, string virtualPath)
{
if (vpp == null) throw new ArgumentNullException(nameof(vpp));
return vpp.FileExists(virtualPath) ? vpp.GetFile(virtualPath).Open() : null;
}
public static IEnumerable<string> ReadLines(this VirtualFile file)
{
if (file == null) throw new ArgumentNullException(nameof(file));
using (var stream = file.Open())
using (var reader = new StreamReader(stream))
using (var e = reader.ReadLines())
while (e.MoveNext())
yield return e.Current;
}
public static string ReadAllText(this VirtualFile file)
{
if (file == null) throw new ArgumentNullException(nameof(file));
using (var stream = file.Open())
using (var reader = new StreamReader(stream))
return reader.ReadToEnd();
}
}
static class RegexExtensions
{
public static T BindNum<T>(this Match match, Func<Group, Group, T> resultor)
{
if (match == null) throw new ArgumentNullException(nameof(match));
if (resultor == null) throw new ArgumentNullException(nameof(resultor));
var groups = match.Groups;
return resultor(groups[1], groups[2]);
}
}
static class StreamExtensions
{
public static long? TryGetLength(this Stream stream)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (!stream.CanSeek) return null;
try { return stream.Length; } catch (NotSupportedException) { return null; }
}
}
static class TextReaderExtensions
{
public static IEnumerator<string> ReadLines(this TextReader reader)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));