-
Notifications
You must be signed in to change notification settings - Fork 754
/
Copy pathAdvancedUrlRewriter.cs
2888 lines (2738 loc) · 163 KB
/
AdvancedUrlRewriter.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
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using DotNetNuke.Application;
using DotNetNuke.Common;
using DotNetNuke.Common.Internal;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Framework;
using DotNetNuke.Services.EventQueue;
#endregion
namespace DotNetNuke.Entities.Urls
{
public class AdvancedUrlRewriter : UrlRewriterBase
{
private static readonly Regex DefaultPageRegex = new Regex(@"(?<!(\?.+))/" + Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex AumDebugRegex = new Regex(@"(&|\?)_aumdebug=[A-Z]+(?:&|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex RewritePathRx = new Regex("(?:&(?<parm>.[^&]+)=$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex UrlSlashesRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled);
#region Private Members
private const string _productName = "AdvancedUrlRewriter";
private FriendlyUrlSettings _settings;
#endregion
#region Overridden Methods
internal override void RewriteUrl(object sender, EventArgs e)
{
Guid parentTraceId = Guid.Empty;
const bool debug = true;
bool failedInitialization = false;
bool ignoreForInstall = false;
var app = (HttpApplication) sender;
try
{
//875 : completely ignore install/upgrade requests immediately
ignoreForInstall = IgnoreRequestForInstall(app.Request);
if (ignoreForInstall == false)
{
_settings = new FriendlyUrlSettings(-1);
SecurityCheck(app);
}
}
catch (Exception ex)
{
//exception handling for advanced Url Rewriting requests
failedInitialization = true;
DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
if (app.Context != null)
{
ShowDebugData(app.Context, app.Request.Url.AbsoluteUri, null, ex);
var action = new UrlAction(app.Request) { Action = ActionType.Output404 };
Handle404OrException(_settings, app.Context, ex, action, false, debug);
}
else
{
throw;
}
}
if (!failedInitialization && !ignoreForInstall)
{
//if made it through there and not installing, go to next call. Not in exception catch because it implements it's own top-level exception handling
var request = app.Context.Request;
//829 : change constructor to stop using physical path
var result = new UrlAction(request)
{
IsSecureConnection = request.IsSecureConnection,
IsSSLOffloaded = IsSSLOffloadEnabled(request),
RawUrl = request.RawUrl
};
ProcessRequest(app.Context,
app.Context.Request.Url,
Host.Host.UseFriendlyUrls,
result,
_settings,
true,
parentTraceId);
}
}
#endregion
#region Public Methods
public void ProcessTestRequestWithContext(HttpContext context,
Uri requestUri,
bool useFriendlyUrls,
UrlAction result,
FriendlyUrlSettings settings)
{
Guid parentTraceId = Guid.Empty;
_settings = settings;
ProcessRequest(context,
requestUri,
useFriendlyUrls,
result,
settings,
false,
parentTraceId);
}
#endregion
#region Private Methods
private PortalAliasInfo GetPortalAlias(FriendlyUrlSettings settings, string requestUrl, out bool redirectAlias, out bool isPrimaryAlias, out string wrongAlias)
{
PortalAliasInfo alias = null;
redirectAlias = false;
wrongAlias = null;
isPrimaryAlias = false;
OrderedDictionary portalRegexes = TabIndexController.GetPortalAliasRegexes(settings);
foreach (string regexPattern in portalRegexes.Keys)
{
//split out the portal alias from the regex pattern representing that alias
var regex = RegexUtils.GetCachedRegex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
var aliasMatch = regex.Match(requestUrl);
if (aliasMatch.Success)
{
//check for mobile browser and matching
var aliasEx = (PortalAliasInfo)portalRegexes[regexPattern];
redirectAlias = aliasEx.Redirect;
if (redirectAlias)
{
wrongAlias = aliasMatch.Groups["alias"].Value;
}
isPrimaryAlias = aliasEx.IsPrimary;
alias = aliasEx;
break;
}
}
return alias;
}
private void ProcessRequest(HttpContext context,
Uri requestUri,
bool useFriendlyUrls,
UrlAction result,
FriendlyUrlSettings settings,
bool allowSettingsChange,
Guid parentTraceId)
{
bool finished = false;
bool showDebug = false;
bool postRequest = false;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string requestType = request.RequestType;
NameValueCollection queryStringCol = request.QueryString;
try
{
string fullUrl, querystring;
//699: get the full url based on the request and the quersytring, rather than the requestUri.ToString()
//there is a difference in encoding, which can corrupt results when an encoded value is in the querystring
RewriteController.GetUrlWithQuerystring(request, requestUri, out fullUrl, out querystring);
showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode);
string ignoreRegex = settings.IgnoreRegex;
bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request);
bool redirectAlias = false;
if (!ignoreRequest)
{
//set original path
context.Items["UrlRewrite:OriginalUrl"] = requestUri.AbsoluteUri;
//set the path of the result object, and determine if a redirect is allowed on this request
result.SetOriginalPath(requestUri.ToString(), settings);
//737 : set the mobile browser
result.SetBrowserType(request, response, settings);
//add to context
context.Items["UrlRewrite:BrowserType"] = result.BrowserType.ToString();
//839 : split out this check
result.SetRedirectAllowed(result.OriginalPath, settings);
//find the portal alias first
string wrongAlias;
bool isPrimaryAlias;
var requestedAlias = GetPortalAlias(settings, fullUrl, out redirectAlias, out isPrimaryAlias, out wrongAlias);
if (requestedAlias != null)
{
//827 : now get the correct settings for this portal (if not a test request)
//839 : separate out redirect check as well and move above first redirect test (ConfigurePortalAliasRedirect)
if (allowSettingsChange)
{
settings = new FriendlyUrlSettings(requestedAlias.PortalID);
result.SetRedirectAllowed(result.OriginalPath, settings);
}
result.PortalAlias = requestedAlias;
result.PrimaryAlias = requestedAlias;//this is the primary alias
result.PortalId = requestedAlias.PortalID;
result.CultureCode = requestedAlias.CultureCode;
//get the portal alias mapping for this portal
result.PortalAliasMapping = PortalSettingsController.Instance().GetPortalAliasMappingMode(requestedAlias.PortalID);
//if requested alias wasn't the primary, we have a replacement, redirects are allowed and the portal alias mapping mode is redirect
//then do a redirect based on the wrong portal
if ((redirectAlias && wrongAlias != null) && result.RedirectAllowed && result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect)
{
//this is the alias, we are going to enforce it as the primary alias
result.PortalAlias = requestedAlias;
result.PrimaryAlias = requestedAlias;
//going to redirect this alias because it is incorrect
//or do we just want to mark as 'check for 301??'
redirectAlias = ConfigurePortalAliasRedirect(ref result,
wrongAlias,
requestedAlias.HTTPAlias,
false,
settings.InternalAliasList,
settings);
}
else
{
//do not redirect the wrong alias, but set the primary alias value
if (wrongAlias != null)
{
//get the portal alias info for the requested alias (which is the wrong one)
//and set that as the alias, but also set the found alias as the primary
PortalAliasInfo wrongAliasInfo = PortalAliasController.Instance.GetPortalAlias(wrongAlias);
if (wrongAliasInfo != null)
{
result.PortalAlias = wrongAliasInfo;
result.PrimaryAlias = requestedAlias;
}
}
}
}
}
ignoreRegex = settings.IgnoreRegex;
ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request);
if (!ignoreRequest)
{
//check to see if a post request
if (request.RequestType == "POST")
{
postRequest = true;
}
//check the portal alias again. This time, in more depth now that the portal Id is known
//this check handles browser types/language specific aliases & mobile aliases
string primaryHttpAlias;
if (!redirectAlias && IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryHttpAlias))
{
//it was an incorrect alias
PortalAliasInfo primaryAlias = PortalAliasController.Instance.GetPortalAlias(primaryHttpAlias);
if (primaryAlias != null) result.PrimaryAlias = primaryAlias;
//try and redirect the alias if the settings allow it
redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings);
}
if (redirectAlias)
{
//not correct alias for portal : will be redirected
//perform a 301 redirect if one has already been found
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.RedirectPermanent(result.FinalUrl, false);
finished = true;
}
if (!finished)
{
//Check to see if this to be rewritten into default.aspx?tabId=nn format
//this call is the main rewriting matching call. It makes the decision on whether it is a
//physical file, whether it is toe be rewritten or redirected by way of a stored rule
//Check if we have a standard url
var uri = new Uri(fullUrl);
if (uri.PathAndQuery.StartsWith("/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase))
{
result.DoRewrite = true;
result.Action = ActionType.CheckFor301;
result.RewritePath = Globals.glbDefaultPage + uri.Query;
}
else
{
bool isPhysicalResource;
CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId);
}
//return 404 if there is no portal alias for a rewritten request
if (result.DoRewrite && result.PortalAlias == null)
{
//882 : move this logic in from where it was before to here
//so that non-rewritten requests don't trip over it
//no portal alias found for the request : that's a 404 error
result.Action = ActionType.Output404;
result.Reason = RedirectReason.No_Portal_Alias;
Handle404OrException(settings, context, null, result, false, showDebug);
finished = true; //cannot fulfil request unless correct portal alias specified
}
}
if (!finished && result.DoRewrite)
{
//check the identified portal alias details for any extra rewrite information required
//this includes the culture and the skin, which can be placed into the rewrite path
//This logic is here because it will catch any Urls which are excluded from rewriting
var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList();
if (result.PortalId > -1 && result.HttpAlias != null)
{
string culture;
string skin;
BrowserTypes browserType;
primaryAliases.GetSettingsByPortalIdAndAlias(result.PortalId, result.HttpAlias,
out culture,
out browserType,
out skin);
//add language code to path if it exists (not null) and if it's not already there
string rewritePath = result.RewritePath;
if (RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, culture))
{
result.CultureCode = culture;
}
//852: add skinSrc to path if it exists and if it's not already there
string debugMessage;
RewriteController.AddSkinToRewritePath(result.TabId, result.PortalId, ref rewritePath, skin, out debugMessage);
result.RewritePath = rewritePath; //reset back from ref temp var
if (debugMessage != null)
{
result.DebugMessages.Add(debugMessage);
}
}
}
if (!finished && result.DoRewrite)
{
//if so, do the rewrite
if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false)
{
if (result.RewritePath.Contains(Globals.glbDefaultPage) == false)
{
RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath);
}
else
{
//if there is no TabId and we have the domain
if (!result.RewritePath.ToLowerInvariant().Contains("tabId="))
{
RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath);
}
else
{
RewriterUtils.RewriteUrl(context, result.RewritePath);
}
}
}
else
{
RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath);
}
}
//confirm which portal the request is for
if (!finished)
{
IdentifyPortalAlias(context, request, requestUri, result, queryStringCol, settings, parentTraceId);
if (result.Action == ActionType.Redirect302Now)
{
//performs a 302 redirect if requested
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.Redirect(result.FinalUrl, false);
finished = true;
}
else
{
if (result.Action == ActionType.Redirect301 && !string.IsNullOrEmpty(result.FinalUrl))
{
finished = true;
//perform a 301 redirect if one has already been found
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.RedirectPermanent(result.FinalUrl, false);
}
}
}
if (!finished)
{
//check to see if this tab has an external url that should be forwared or not
finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId);
}
//check for a parameter redirect (we had to do all the previous processing to know we are on the right portal and identify the tabid)
//if the CustomParmRewrite flag is set, it means we already rewrote these parameters, so they have to be correct, and aren't subject to
//redirection. The only reason to do a custom parm rewrite is to interpret already-friendly parameters
if (!finished
&& !postRequest /* either request is null, or it's not a post - 551 */
&& result.HttpAlias != null /* must have a http alias */
&& !result.CustomParmRewrite && /* not custom rewritten parms */
((settings.EnableCustomProviders &&
RedirectController.CheckForModuleProviderRedirect(requestUri, ref result, queryStringCol, settings, parentTraceId))
//894 : allow disable of all custom providers
||
RedirectController.CheckForParameterRedirect(requestUri, ref result, queryStringCol, settings)))
{
//301 redirect to new location based on parameter match
if (response != null)
{
switch (result.Action)
{
case ActionType.Redirect301:
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.RedirectPermanent(result.FinalUrl);
break;
case ActionType.Redirect302:
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.Redirect(result.FinalUrl);
break;
case ActionType.Output404:
response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " "));
Handle404OrException(settings, context, null, result, true, showDebug);
break;
}
}
finished = true;
}
//shifted until after the 301 redirect code to allow redirects to be checked for pages which have no rewrite value
//look for a 404 result from the rewrite, because of a deleted page or rule
if (!finished && result.Action == ActionType.Output404)
{
if (result.OriginalPath.Equals(result.HttpAlias, StringComparison.InvariantCultureIgnoreCase)
&& result.PortalAlias != null
&& result.Reason != RedirectReason.Deleted_Page
&& result.Reason != RedirectReason.Disabled_Page)
{
//Request for domain with no page identified (and no home page set in Site Settings)
result.Action = ActionType.Continue;
}
else
{
finished = true;
response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " "));
if (showDebug)
{
ShowDebugData(context, requestUri.AbsoluteUri, result, null);
}
//show the 404 page if configured
result.Reason = RedirectReason.Requested_404;
Handle404OrException(settings, context, null, result, true, showDebug);
}
}
if (!finished)
{
//add the portal settings to the app context if the portal alias has been found and is correct
if (result.PortalId != -1 && result.PortalAlias != null)
{
//for invalid tab id other than -1, show the 404 page
TabInfo tabInfo = TabController.Instance.GetTab(result.TabId, result.PortalId, false);
if (tabInfo == null && result.TabId > -1)
{
finished = true;
if (showDebug)
{
ShowDebugData(context, requestUri.AbsoluteUri, result, null);
}
//show the 404 page if configured
result.Action = ActionType.Output404;
result.Reason = RedirectReason.Requested_404;
response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " "));
Handle404OrException(settings, context, null, result, true, showDebug);
}
else
{
Globals.SetApplicationName(result.PortalId);
// load the PortalSettings into current context
var portalSettings = new PortalSettings(result.TabId, result.PortalAlias);
//set the primary alias if one was specified
if (result.PrimaryAlias != null) portalSettings.PrimaryAlias = result.PrimaryAlias;
if (result.CultureCode != null && fullUrl.Contains(result.CultureCode) &&
portalSettings.DefaultLanguage == result.CultureCode)
{
//when the request culture code is the same as the portal default, check for a 301 redirect, because we try and remove the language from the url where possible
result.Action = ActionType.CheckFor301;
}
int portalHomeTabId = portalSettings.HomeTabId;
if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings"))
{
context.Items.Add("PortalSettings", portalSettings);
// load PortalSettings and HostSettings dictionaries into current context
// specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way
context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalSettings.PortalId));
context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary());
}
//check if a secure redirection is needed
//this would be done earlier in the piece, but need to know the portal settings, tabid etc before processing it
bool redirectSecure = CheckForSecureRedirect(portalSettings, requestUri, result, queryStringCol, settings);
if (redirectSecure)
{
if (response != null)
{
//702 : don't check final url until checked for null reference first
if (result.FinalUrl != null)
{
if (result.FinalUrl.StartsWith("https://"))
{
if (showDebug)
{
/*
string debugMsg = "{0}, {1}, {2}, {3}, {4}";
string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString();
response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer));
*/
ShowDebugData(context, fullUrl, result, null);
}
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.RedirectPermanent(result.FinalUrl);
finished = true;
}
else
{
if (settings.SSLClientRedirect)
{
//redirect back to http version, use client redirect
response.Clear();
// add a refresh header to the response
response.AddHeader("Refresh", "0;URL=" + result.FinalUrl);
// add the clientside javascript redirection script
var finalUrl = HttpUtility.HtmlEncode(result.FinalUrl);
response.Write("<html><head><title></title>");
response.Write(@"<!-- <script language=""javascript"">window.location.replace(""" + finalUrl + @""")</script> -->");
response.Write("</head><body><div><a href='" + finalUrl + "'>" + finalUrl + "</a></div></body></html>");
if (showDebug)
{
/*
string debugMsg = "{0}, {1}, {2}, {3}, {4}";
string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString();
response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer));
*/
ShowDebugData(context, fullUrl, result, null);
}
// send the response
//891 : reinstate the response.end to stop the entire page loading
response.End();
finished = true;
}
else
{
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.RedirectPermanent(result.FinalUrl);
finished = true;
}
}
}
}
}
else
{
//check for, and do a 301 redirect if required
if (CheckForRedirects(requestUri, fullUrl, queryStringCol, result, requestType, settings, portalHomeTabId))
{
if (response != null)
{
if (result.Action == ActionType.Redirect301)
{
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.RedirectPermanent(result.FinalUrl, false);
finished = true;
}
else if (result.Action == ActionType.Redirect302)
{
response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested");
response.Redirect(result.FinalUrl, false);
finished = true;
}
}
}
else
{
//612 : Don't clear out a 302 redirect if set
if (result.Action != ActionType.Redirect302 &&
result.Action != ActionType.Redirect302Now)
{
result.Reason = RedirectReason.Not_Redirected;
result.FinalUrl = null;
}
}
}
}
}
else
{
// alias does not exist in database
// and all attempts to find another have failed
//this should only happen if the HostPortal does not have any aliases
result.Action = ActionType.Output404;
if (response != null)
{
if (showDebug)
{
ShowDebugData(context, fullUrl, result, null);
}
result.Reason = RedirectReason.Requested_404;
//912 : change 404 type to transfer to allow transfer to main portal in single-portal installs
Handle404OrException(settings, context, null, result, true, showDebug);
finished = true;
}
}
}
//404 page ??
if (settings.TabId404 > 0 && settings.TabId404 == result.TabId)
{
string status = queryStringCol["status"];
if (status == "404")
{
//respond with a 404 error
result.Action = ActionType.Output404;
result.Reason = RedirectReason.Requested_404_In_Url;
Handle404OrException(settings, context, null, result, true, showDebug);
}
}
else
{
if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished &&
result.Action == ActionType.Continue)
{
//739 : catch no-extension 404 errors
string pathWithNoQs = result.OriginalPath;
if (pathWithNoQs.Contains("?"))
{
pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal));
}
if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains("."))
{
//no page extension, output a 404 if the Url is not found
//766 : check for physical path before passing off as a 404 error
//829 : change to use action physical path
//893 : filter by regex pattern to exclude urls which are valid, but show up as extensionless
if ((request != null && Directory.Exists(result.PhysicalPath))
||
Regex.IsMatch(pathWithNoQs, settings.ValidExtensionlessUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
{
//do nothing : it's a request for a valid physical path, maybe including a default document
result.VirtualPath = StateBoolean.False;
}
else
{
if (!Globals.ServicesFrameworkRegex.IsMatch(context.Request.RawUrl))
{
//no physical path, intercept the request and hand out a 404 error
result.Action = ActionType.Output404;
result.Reason = RedirectReason.Page_404;
result.VirtualPath = StateBoolean.True;
//add in a message to explain this 404, becaue it can be cryptic
result.DebugMessages.Add("404 Reason : Not found and no extension");
Handle404OrException(settings, context, null, result, true, showDebug);
}
}
}
}
}
// show debug messages after extensionless-url special 404 handling
if (showDebug)
{
ShowDebugData(context, fullUrl, result, null);
}
}
}
catch (ThreadAbortException)
{
//do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest
//level try/catch block, so we handle it here.
Thread.ResetAbort();
}
catch (Exception ex)
{
if (showDebug)
{
Services.Exceptions.Exceptions.LogException(ex);
}
if (response != null)
{
if (showDebug)
{
ShowDebugData(context, requestUri.AbsoluteUri, result, ex);
}
if (result != null)
{
result.Ex = ex;
result.Reason = RedirectReason.Exception;
}
Handle404OrException(settings, context, ex, result, false, showDebug);
}
else
{
if (result != null && result.DebugMessages != null)
{
result.DebugMessages.Add("Exception: " + ex.Message);
result.DebugMessages.Add("Stack Trace: " + ex.StackTrace);
}
throw;
}
}
finally
{
//809 : add in new code copied from urlRewrite class in standard Url Rewrite module
if (context != null && context.Items["FirstRequest"] != null)
{
context.Items.Remove("FirstRequest");
//process any messages in the eventQueue for the Application_Start_FIrstRequest event
EventQueueController.ProcessMessages("Application_Start_FirstRequest");
}
}
}
private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex)
{
if (context != null)
{
HttpResponse response = context.Response;
//handle null responses wherever they might be found - this routine must be tolerant to all kinds of invalid inputs
if (requestUri == null)
{
requestUri = "null Uri";
}
string finalUrl = "null final Url";
string rewritePath = "null rewrite path";
string action = "null action";
if (result != null)
{
finalUrl = result.FinalUrl;
action = result.Action.ToString();
rewritePath = result.RewritePath;
}
//format up the error message to show
const string debugMsg = "{0}, {1}, {2}, {3}, {4}, {5}, {6}";
string productVer = DotNetNukeContext.Current.Application.Version.ToString();
string portalSettings = "";
string browser = "Unknown";
//949 : don't rely on 'result' being non-null
if (result != null)
{
browser = result.BrowserType.ToString();
}
if (context.Items.Contains("PortalSettings"))
{
var ps = (PortalSettings) context.Items["PortalSettings"];
if (ps != null)
{
portalSettings = ps.PortalId.ToString();
if (ps.PortalAlias != null)
{
portalSettings += ":" + ps.PortalAlias.HTTPAlias;
}
}
}
response.AppendHeader("X-" + _productName + "-Debug",
string.Format(debugMsg, requestUri, finalUrl, rewritePath, action, productVer,
portalSettings, browser));
int msgNum = 1;
if (result != null)
{
foreach (string msg in result.DebugMessages)
{
response.AppendHeader("X-" + _productName + "-Debug-" + msgNum.ToString("00"), msg);
msgNum++;
}
}
if (ex != null)
{
response.AppendHeader("X-" + _productName + "-Ex", ex.Message);
}
}
}
private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug)
{
//handle Auto-Add Alias
if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias())
{
//Need to determine if this is a real 404 or a possible new alias.
var portalId = Host.Host.HostPortalID;
if (portalId > Null.NullInteger)
{
if (string.IsNullOrEmpty(result.DomainName))
{
result.DomainName = Globals.GetDomainName(context.Request); //parse the domain name out of the request
}
//Get all the existing aliases
var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList();
bool autoaddAlias;
bool isPrimary = false;
if (!aliases.Any())
{
autoaddAlias = true;
isPrimary = true;
}
else
{
autoaddAlias = true;
foreach (var alias in aliases)
{
if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0
&& result.DomainName.Length >= alias.HTTPAlias.Length)
{
autoaddAlias = false;
break;
}
}
}
if (autoaddAlias)
{
var portalAliasInfo = new PortalAliasInfo
{
PortalID = portalId,
HTTPAlias = result.DomainName,
IsPrimary = isPrimary
};
PortalAliasController.Instance.AddPortalAlias(portalAliasInfo);
context.Response.Redirect(context.Request.Url.ToString(), true);
}
}
}
if (context != null)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
HttpServerUtility server = context.Server;
const string errorPageHtmlHeader = @"<html><head><title>{0}</title></head><body>";
const string errorPageHtmlFooter = @"</body></html>";
var errorPageHtml = new StringWriter();
CustomErrorsSection ceSection = null;
//876 : security catch for custom error reading
try
{
ceSection = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors");
}
// ReSharper disable EmptyGeneralCatchClause
catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
{
//on some medium trust environments, this will throw an exception for trying to read the custom Errors
//do nothing
}
/* 454 new 404/500 error handling routine */
bool useDNNTab = false;
int errTabId = -1;
string errUrl = null;
string status = "";
bool isPostback = false;
if (settings != null)
{
if (request.RequestType == "POST")
{
isPostback = true;
}
if (result != null && ex != null)
{
result.DebugMessages.Add("Exception: " + ex.Message);
result.DebugMessages.Add("Stack Trace: " + ex.StackTrace);
if (ex.InnerException != null)
{
result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message);
result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace);
}
else
{
result.DebugMessages.Add("Inner Ex : null");
}
}
string errRH;
string errRV;
int statusCode;
if (result != null && result.Action != ActionType.Output404)
{
//output everything but 404 (usually 500)
if (settings.TabId500 > -1) //tabid specified for 500 error page, use that
{
useDNNTab = true;
errTabId = settings.TabId500;
}
errUrl = settings.Url500;
errRH = "X-UrlRewriter-500";
errRV = "500 Rewritten to {0} : {1}";
statusCode = 500;
status = "500 Internal Server Error";
}
else //output 404 error
{
if (settings.TabId404 > -1) //if the tabid is specified for a 404 page, then use that
{
useDNNTab = true;
errTabId = settings.TabId404;
}
if (!String.IsNullOrEmpty(settings.Regex404))
//with 404 errors, there's an option to catch certain urls and use an external url for extra processing.
{
try
{
//944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error
string requestedUrl = request.Url.ToString();
if (result != null && !string.IsNullOrEmpty(result.OriginalPath))
{
requestedUrl = result.OriginalPath;
}
if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
{
useDNNTab = false;
//if we have a match in the 404 regex value, then don't use the tabid
}
}
catch (Exception regexEx)
{
//.some type of exception : output in response header, and go back to using the tabid
response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message);
}
}
errUrl = settings.Url404;
errRH = "X-UrlRewriter-404";
errRV = "404 Rewritten to {0} : {1} : Reason {2}";
status = "404 Not Found";
statusCode = 404;
}
// check for 404 logging
if ((result == null || result.Action == ActionType.Output404))
{
//Log 404 errors to Event Log
UrlRewriterUtils.Log404(request, settings, result);
}
//912 : use unhandled 404 switch
string reason404 = null;
bool unhandled404 = true;
if (useDNNTab && errTabId > -1)
{
unhandled404 = false; //we're handling it here
TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true);
if (errTab != null)
{