/
HttpHandlerFactory.cs
399 lines (329 loc) · 16.8 KB
/
HttpHandlerFactory.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using ServiceStack.Host;
using ServiceStack.Host.AspNet;
using ServiceStack.Host.Handlers;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack
{
public class HttpHandlerFactory : IHttpHandlerFactory
{
static readonly List<string> WebHostRootFileNames = new List<string>();
static private readonly string WebHostPhysicalPath = null;
static private readonly string DefaultRootFileName = null;
//internal static string ApplicationBaseUrl = null;
static private readonly IHttpHandler DefaultHttpHandler = null;
static private readonly RedirectHttpHandler NonRootModeDefaultHttpHandler = null;
static private readonly IHttpHandler ForbiddenHttpHandler = null;
static private readonly IHttpHandler NotFoundHttpHandler = null;
static private readonly IHttpHandler StaticFilesHandler = new StaticFileHandler();
private static readonly bool IsIntegratedPipeline = false;
private static readonly bool HostAutoRedirectsDirs = false;
[ThreadStatic]
public static string DebugLastHandlerArgs;
static HttpHandlerFactory()
{
try
{
//MONO doesn't implement this property
var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline");
if (pi != null)
{
IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]);
}
var appHost = HostContext.AppHost;
var config = appHost.Config;
var isAspNetHost = HostContext.IsAspNetHost;
WebHostPhysicalPath = appHost.VirtualPathProvider.RootDirectory.RealPath;
HostAutoRedirectsDirs = isAspNetHost && !Env.IsMono;
//Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources
var hostedAtRootPath = config.HandlerFactoryPath == null;
//DefaultHttpHandler not supported in IntegratedPipeline mode
if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono)
DefaultHttpHandler = new DefaultHttpHandler();
var rootFiles = appHost.VirtualPathProvider.GetRootFiles().ToList();
foreach (var file in rootFiles)
{
var fileNameLower = file.Name.ToLower();
if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower))
{
//Can't serve Default.aspx pages so ignore and allow for next default document
if (!fileNameLower.EndsWith(".aspx"))
{
DefaultRootFileName = fileNameLower;
StaticFileHandler.SetDefaultFile(file.VirtualPath, file.ReadAllBytes(), file.LastModified);
if (DefaultHttpHandler == null)
DefaultHttpHandler = new StaticFileHandler { VirtualNode = file };
}
}
WebHostRootFileNames.Add(fileNameLower);
}
foreach (var dir in appHost.VirtualPathProvider.GetRootDirectories())
{
WebHostRootFileNames.Add(dir.Name.ToLower());
}
if (!string.IsNullOrEmpty(config.DefaultRedirectPath))
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.DefaultRedirectPath };
if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath))
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath };
if (!string.IsNullOrEmpty(config.MetadataRedirectPath))
NonRootModeDefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath };
if (DefaultHttpHandler == null)
DefaultHttpHandler = NotFoundHttpHandler;
var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler;
var debugDefaultHandler = defaultRedirectHanlder != null
? defaultRedirectHanlder.RelativeUrl
: typeof(DefaultHttpHandler).GetOperationName();
SetApplicationBaseUrl(config.WebHostUrl);
ForbiddenHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden);
if (ForbiddenHttpHandler == null)
{
ForbiddenHttpHandler = new ForbiddenHttpHandler
{
IsIntegratedPipeline = IsIntegratedPipeline,
WebHostPhysicalPath = WebHostPhysicalPath,
WebHostRootFileNames = WebHostRootFileNames,
WebHostUrl = config.WebHostUrl,
DefaultRootFileName = DefaultRootFileName,
DefaultHandler = debugDefaultHandler,
};
}
NotFoundHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.NotFound);
if (NotFoundHttpHandler == null)
{
NotFoundHttpHandler = new NotFoundHttpHandler
{
IsIntegratedPipeline = IsIntegratedPipeline,
WebHostPhysicalPath = WebHostPhysicalPath,
WebHostRootFileNames = WebHostRootFileNames,
WebHostUrl = config.WebHostUrl,
DefaultRootFileName = DefaultRootFileName,
DefaultHandler = debugDefaultHandler,
};
}
}
catch (Exception ex)
{
HostContext.AppHost.OnStartupException(ex);
}
}
// Entry point for ASP.NET
public IHttpHandler GetHandler(HttpContext ctx, string requestType, string url, string pathTranslated)
{
var context = ctx.Request.RequestContext.HttpContext;
var appHost = HostContext.AppHost;
DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated;
//var httpReq = new AspNetRequest(context, url);
var httpReq = new AspNetRequest(context, url.SanitizedVirtualPath());
foreach (var rawHttpHandler in appHost.RawHttpHandlers)
{
var reqInfo = rawHttpHandler(httpReq);
if (reqInfo != null) return reqInfo;
}
var mode = appHost.Config.HandlerFactoryPath;
var pathInfo = context.Request.GetPathInfo();
//WebDev Server auto requests '/default.aspx' so recorrect path to different default document
if (mode == null && (url == "/default.aspx" || url == "/Default.aspx"))
pathInfo = "/";
//Default Request /
if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
{
//If the fallback route can handle it, let it
if (appHost.Config.FallbackRestPath != null)
{
string contentType;
var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out contentType);
var restPath = appHost.Config.FallbackRestPath(context.Request.HttpMethod, sanitizedPath, pathTranslated);
if (restPath != null)
{
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
}
}
//Exception calling context.Request.Url on Apache+mod_mono
var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl();
SetApplicationBaseUrl(absoluteUrl);
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
if (catchAllHandler != null) return catchAllHandler;
if (mode == null)
return DefaultHttpHandler;
if (DefaultRootFileName != null)
return StaticFilesHandler;
return NonRootModeDefaultHttpHandler;
}
if (mode != null && pathInfo.EndsWith("/" + mode))
{
return ReturnDefaultHandler(httpReq);
}
return GetHandlerForPathInfo(
httpReq.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated)
?? NotFoundHttpHandler;
}
private static void SetApplicationBaseUrl(string absoluteUrl)
{
if (absoluteUrl == null) return;
var defaultRedirectUrl = DefaultHttpHandler as RedirectHttpHandler;
if (defaultRedirectUrl != null && defaultRedirectUrl.AbsoluteUrl == null)
defaultRedirectUrl.AbsoluteUrl = absoluteUrl.CombineWith(
defaultRedirectUrl.RelativeUrl);
if (NonRootModeDefaultHttpHandler != null && NonRootModeDefaultHttpHandler.AbsoluteUrl == null)
NonRootModeDefaultHttpHandler.AbsoluteUrl = absoluteUrl.CombineWith(
NonRootModeDefaultHttpHandler.RelativeUrl);
}
public static string GetBaseUrl()
{
return HostContext.Config.WebHostUrl;
}
// Entry point for HttpListener
public static IHttpHandler GetHandler(IHttpRequest httpReq)
{
var appHost = HostContext.AppHost;
foreach (var rawHttpHandler in appHost.RawHttpHandlers)
{
var reqInfo = rawHttpHandler(httpReq);
if (reqInfo != null) return reqInfo;
}
var mode = appHost.Config.HandlerFactoryPath;
var pathInfo = httpReq.PathInfo;
//Default Request /
if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
{
//If the fallback route can handle it, let it
if (appHost.Config.FallbackRestPath != null)
{
string contentType;
var sanitizedPath = RestHandler.GetSanitizedPathInfo(pathInfo, out contentType);
var restPath = appHost.Config.FallbackRestPath(httpReq.HttpMethod, sanitizedPath, httpReq.GetPhysicalPath());
if (restPath != null)
{
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
}
}
SetApplicationBaseUrl(httpReq.GetPathUrl());
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
if (catchAllHandler != null) return catchAllHandler;
if (mode == null)
return DefaultHttpHandler;
if (DefaultRootFileName != null)
return StaticFilesHandler;
return NonRootModeDefaultHttpHandler;
}
if (mode != null && pathInfo.EndsWith("/" + mode))
{
return ReturnDefaultHandler(httpReq);
}
return GetHandlerForPathInfo(httpReq.HttpMethod, pathInfo, pathInfo, httpReq.GetPhysicalPath())
?? NotFoundHttpHandler;
}
private static IHttpHandler ReturnDefaultHandler(IHttpRequest httpReq)
{
var pathProvider = HostContext.VirtualFileSources;
var defaultDoc = pathProvider.GetFile(DefaultRootFileName ?? "");
if (httpReq.GetPhysicalPath() != WebHostPhysicalPath
|| defaultDoc == null)
{
return new IndexPageHttpHandler();
}
var okToServe = ShouldAllow(httpReq.GetPhysicalPath());
return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler;
}
internal static IHttpHandler ReturnRequestInfo(IHttpRequest httpReq)
{
if ((HostContext.DebugMode
|| HostContext.Config.AdminAuthSecret != null)
&& httpReq.QueryString[Keywords.Debug] == Keywords.RequestInfo)
{
if (HostContext.DebugMode || HostContext.HasValidAuthSecret(httpReq))
{
var reqInfo = RequestInfoHandler.GetRequestInfo(httpReq);
reqInfo.Host = HostContext.Config.DebugHttpListenerHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + HostContext.ServiceName;
reqInfo.PathInfo = httpReq.PathInfo;
reqInfo.GetPathUrl = httpReq.GetPathUrl();
return new RequestInfoHandler { RequestInfo = reqInfo };
}
}
return null;
}
// no handler registered
// serve the file from the filesystem, restricting to a safelist of extensions
private static bool ShouldAllow(string filePath)
{
var fileExt = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileExt)) return false;
return HostContext.Config.AllowFileExtensions.Contains(fileExt.Substring(1));
}
public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath)
{
var appHost = HostContext.AppHost;
var pathParts = pathInfo.TrimStart('/').Split('/');
if (pathParts.Length == 0) return NotFoundHttpHandler;
string contentType;
var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType);
if (restPath != null)
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
var existingFile = pathParts[0].ToLower();
if (WebHostRootFileNames.Contains(existingFile))
{
var fileExt = System.IO.Path.GetExtension(filePath);
var isFileRequest = !string.IsNullOrEmpty(fileExt);
if (!isFileRequest && !HostAutoRedirectsDirs)
{
//If pathInfo is for Directory try again with redirect including '/' suffix
if (!pathInfo.EndsWith("/"))
{
var appFilePath = filePath.Substring(0, filePath.Length - requestPath.Length);
var redirect = Host.Handlers.StaticFileHandler.DirectoryExists(filePath, appFilePath);
if (redirect)
{
return new RedirectHttpHandler
{
RelativeUrl = pathInfo + "/",
};
}
}
}
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
if (catchAllHandler != null) return catchAllHandler;
if (!isFileRequest)
{
return appHost.VirtualPathProvider.DirectoryExists(pathInfo)
? StaticFilesHandler
: NotFoundHttpHandler;
}
return ShouldAllow(requestPath)
? StaticFilesHandler
: ForbiddenHttpHandler;
}
var handler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
if (handler != null) return handler;
if (appHost.Config.FallbackRestPath != null)
{
restPath = appHost.Config.FallbackRestPath(httpMethod, pathInfo, filePath);
if (restPath != null)
{
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
}
}
return null;
}
private static IHttpHandler GetCatchAllHandlerIfAny(string httpMethod, string pathInfo, string filePath)
{
foreach (var httpHandlerResolver in HostContext.CatchAllHandlers)
{
var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath);
if (httpHandler != null)
return httpHandler;
}
return null;
}
public void ReleaseHandler(IHttpHandler handler)
{
}
}
}