This repository was archived by the owner on Jul 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEndpointHandlerBase.cs
More file actions
236 lines (202 loc) · 8.15 KB
/
EndpointHandlerBase.cs
File metadata and controls
236 lines (202 loc) · 8.15 KB
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
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SimpleStack.Logging;
using SimpleStack.Extensions;
using SimpleStack.Interfaces;
using SimpleStack.Enums;
using SimpleStack.Serializers;
using System.Runtime.Serialization;
using System.Net;
using System.ServiceModel;
namespace SimpleStack
{
public abstract class EndpointHandlerBase : ISimpleStackHttpHandler//, IHttpHandler
{
internal static readonly ILog Log = Logger.CreateLog ();
internal static readonly Dictionary<byte[], byte[]> NetworkInterfaceIpv4Addresses = new Dictionary<byte[], byte[]> ();
internal static readonly byte[][] NetworkInterfaceIpv6Addresses = new byte[0][];
public string RequestName { get; set; }
static EndpointHandlerBase ()
{
try {
IPAddressExtensions.GetAllNetworkInterfaceIpv4Addresses ().ForEach ((x, y) => NetworkInterfaceIpv4Addresses [x.GetAddressBytes ()] = y.GetAddressBytes ());
NetworkInterfaceIpv6Addresses = IPAddressExtensions.GetAllNetworkInterfaceIpv6Addresses ().ConvertAll (x => x.GetAddressBytes ()).ToArray ();
} catch (Exception ex) {
Log.Warn ("Failed to retrieve IP Addresses, some security restriction features may not work: " + ex.Message, ex);
}
}
public EndpointAttributes HandlerAttributes { get; set; }
public bool IsReusable {
get { return false; }
}
public abstract object CreateRequest (IHttpRequest request, string operationName);
public abstract object GetResponse (IHttpRequest httpReq, IHttpResponse httpRes, object request);
public virtual void ProcessRequest (IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
{
throw new NotImplementedException ();
}
public static object DeserializeHttpRequest (Type operationType, IHttpRequest httpReq, string contentType)
{
var httpMethod = httpReq.HttpMethod;
var queryString = httpReq.QueryString;
if (httpMethod == HttpMethods.Get || httpMethod == HttpMethods.Delete || httpMethod == HttpMethods.Options) {
try {
return KeyValueDataContractDeserializer.Instance.Parse (queryString, operationType);
} catch (Exception ex) {
var msg = "Could not deserialize '{0}' request using KeyValueDataContractDeserializer: '{1}'.\nError: '{2}'"
.Fmt (operationType, queryString, ex);
throw new SerializationException (msg);
}
}
var isFormData = httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData);
if (isFormData) {
try {
return KeyValueDataContractDeserializer.Instance.Parse (httpReq.FormData, operationType);
} catch (Exception ex) {
throw new SerializationException ("Error deserializing FormData: " + httpReq.FormData, ex);
}
}
var request = CreateContentTypeRequest (httpReq, operationType, contentType);
return request;
}
protected static object CreateContentTypeRequest (IHttpRequest httpReq, Type requestType, string contentType)
{
try {
if (!string.IsNullOrEmpty (contentType) && httpReq.ContentLength > 0) {
var deserializer = EndpointHost.AppHost.ContentTypeFilters.GetStreamDeserializer (contentType);
if (deserializer != null) {
return deserializer (requestType, httpReq.InputStream);
}
}
} catch (Exception ex) {
var msg = "Could not deserialize '{0}' request using {1}'\nError: {2}"
.Fmt (contentType, requestType, ex);
throw new SerializationException (msg);
}
return requestType.CreateInstance (); //Return an empty DTO, even for empty request bodies
}
protected static object GetCustomRequestFromBinder (IHttpRequest httpReq, Type requestType)
{
Func<IHttpRequest, object> requestFactoryFn;
(ServiceManager ?? EndpointHost.ServiceManager).ServiceController.RequestTypeFactoryMap.TryGetValue (
requestType, out requestFactoryFn);
return requestFactoryFn != null ? requestFactoryFn (httpReq) : null;
}
// protected static bool DefaultHandledRequest(HttpListenerContext context)
// {
// return false;
// }
//
// protected static bool DefaultHandledRequest(HttpContext context)
// {
// return false;
// }
// public virtual void ProcessRequest (Dictionary<string,string> context)
// {
// var operationName = this.RequestName ?? context.Request.GetOperationName ();
//
// if (string.IsNullOrEmpty (operationName))
// return;
//
// //if (DefaultHandledRequest(context)) return;
//
// ProcessRequest (
// new HttpRequestWrapper (operationName, context.Request),
// new HttpResponseWrapper (context.Response),
// operationName);
// }
//
// public virtual void ProcessRequest(HttpListenerContext context)
// {
// var operationName = this.RequestName ?? context.Request.GetOperationName();
//
// if (string.IsNullOrEmpty(operationName)) return;
//
// if (DefaultHandledRequest(context)) return;
//
// ProcessRequest(
// new HttpListenerRequestWrapper(operationName, context.Request),
// new HttpListenerResponseWrapper(context.Response),
// operationName);
// }
public static ServiceManager ServiceManager { get; set; }
public static Type GetOperationType (string operationName)
{
return ServiceManager != null
? ServiceManager.Metadata.GetOperationType (operationName)
: EndpointHost.Metadata.GetOperationType (operationName);
}
protected static object ExecuteService (object request,
EndpointAttributes endpointAttributes,
IHttpRequest httpReq,
IHttpResponse httpRes)
{
return EndpointHost.ExecuteService (request, endpointAttributes, httpReq, httpRes);
}
public EndpointAttributes GetEndpointAttributes (System.ServiceModel.OperationContext operationContext)
{
if (!EndpointHost.Config.EnableAccessRestrictions)
return default(EndpointAttributes);
var portRestrictions = default(EndpointAttributes);
var ipAddress = GetIpAddress (operationContext);
portRestrictions |= EndpointAttributesExtensions.GetAttributes (ipAddress);
//TODO: work out if the request was over a secure channel
//portRestrictions |= request.IsSecureConnection ? PortRestriction.Secure : PortRestriction.InSecure;
return portRestrictions;
}
public static IPAddress GetIpAddress (System.ServiceModel.OperationContext context)
{
#if !MONO
var prop = context.IncomingMessageProperties;
if (context.IncomingMessageProperties.ContainsKey (System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name)) {
var endpoint = prop [System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name]
as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
if (endpoint != null) {
return IPAddress.Parse (endpoint.Address);
}
}
#endif
return null;
}
protected static void AssertOperationExists (string operationName, Type type)
{
if (type == null) {
throw new NotImplementedException (
string.Format ("The operation '{0}' does not exist for this service", operationName));
}
}
protected void HandleException (IHttpRequest httpReq, IHttpResponse httpRes, string operationName, Exception ex)
{
var errorMessage = string.Format ("Error occured while Processing Request: {0}", ex.Message);
Log.Error (errorMessage, ex);
try {
EndpointHost.ExceptionHandler (httpReq, httpRes, operationName, ex);
} catch (Exception writeErrorEx) {
//Exception in writing to response should not hide the original exception
Log.Info ("Failed to write error to response: {0}", writeErrorEx);
//rethrow the original exception
throw ex;
} finally {
httpRes.EndServiceStackRequest(skipHeaders: true);
}
}
protected bool AssertAccess (IHttpRequest httpReq, IHttpResponse httpRes, Feature feature, string operationName)
{
if (operationName == null)
throw new ArgumentNullException ("operationName");
if (EndpointHost.Config.EnableFeatures != Feature.All) {
if (!EndpointHost.Config.HasFeature (feature)) {
EndpointHost.Config.HandleErrorResponse (httpReq, httpRes, HttpStatusCode.Forbidden, "Feature Not Available");
return false;
}
}
var format = feature.ToFormat ();
if (!EndpointHost.Metadata.CanAccess (httpReq, format, operationName)) {
EndpointHost.Config.HandleErrorResponse (httpReq, httpRes, HttpStatusCode.Forbidden, "Service Not Available");
return false;
}
return true;
}
}
}