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
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
#pragma warning disable 1634, 1691
namespace System.ServiceModel.Web
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Net;
using System.Net.Mime;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
public class IncomingWebRequestContext
{
static readonly string HttpGetMethod = "GET";
static readonly string HttpHeadMethod = "HEAD";
static readonly string HttpPutMethod = "PUT";
static readonly string HttpPostMethod = "POST";
static readonly string HttpDeleteMethod = "DELETE";
Collection<ContentType> cachedAcceptHeaderElements;
string acceptHeaderWhenHeaderElementsCached;
internal const string UriTemplateMatchResultsPropertyName = "UriTemplateMatchResults";
OperationContext operationContext;
internal IncomingWebRequestContext(OperationContext operationContext)
{
Fx.Assert(operationContext != null, "operationContext is null");
this.operationContext = operationContext;
}
public string Accept
{
get { return EnsureMessageProperty().Headers[HttpRequestHeader.Accept]; }
}
public long ContentLength
{
get { return long.Parse(this.EnsureMessageProperty().Headers[HttpRequestHeader.ContentLength], CultureInfo.InvariantCulture); }
}
public string ContentType
{
get { return this.EnsureMessageProperty().Headers[HttpRequestHeader.ContentType]; }
}
public IEnumerable<string> IfMatch
{
get
{
string ifMatchHeader = MessageProperty.Headers[HttpRequestHeader.IfMatch];
return (string.IsNullOrEmpty(ifMatchHeader)) ? null : Utility.QuoteAwareStringSplit(ifMatchHeader);
}
}
public IEnumerable<string> IfNoneMatch
{
get
{
string ifNoneMatchHeader = MessageProperty.Headers[HttpRequestHeader.IfNoneMatch];
return (string.IsNullOrEmpty(ifNoneMatchHeader)) ? null : Utility.QuoteAwareStringSplit(ifNoneMatchHeader);
}
}
public DateTime? IfModifiedSince
{
get
{
string dateTime = this.MessageProperty.Headers[HttpRequestHeader.IfModifiedSince];
if (!string.IsNullOrEmpty(dateTime))
{
DateTime parsedDateTime;
if (HttpDateParse.ParseHttpDate(dateTime, out parsedDateTime))
{
return parsedDateTime;
}
}
return null;
}
}
public DateTime? IfUnmodifiedSince
{
get
{
string dateTime = this.MessageProperty.Headers[HttpRequestHeader.IfUnmodifiedSince];
if (!string.IsNullOrEmpty(dateTime))
{
DateTime parsedDateTime;
if (HttpDateParse.ParseHttpDate(dateTime, out parsedDateTime))
{
return parsedDateTime;
}
}
return null;
}
}
public WebHeaderCollection Headers
{
get { return this.EnsureMessageProperty().Headers; }
}
public string Method
{
get { return this.EnsureMessageProperty().Method; }
}
public UriTemplateMatch UriTemplateMatch
{
get
{
if (this.operationContext.IncomingMessageProperties.ContainsKey(UriTemplateMatchResultsPropertyName))
{
return this.operationContext.IncomingMessageProperties[UriTemplateMatchResultsPropertyName] as UriTemplateMatch;
}
else
{
return null;
}
}
set
{
this.operationContext.IncomingMessageProperties[UriTemplateMatchResultsPropertyName] = value;
}
}
public string UserAgent
{
get { return this.EnsureMessageProperty().Headers[HttpRequestHeader.UserAgent]; }
}
HttpRequestMessageProperty MessageProperty
{
get
{
if (operationContext.IncomingMessageProperties == null)
{
return null;
}
if (!operationContext.IncomingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
{
return null;
}
return operationContext.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
}
}
public void CheckConditionalRetrieve(string entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtagFromString(entityTag);
CheckConditionalRetrieveWithValidatedEtag(validEtag);
}
public void CheckConditionalRetrieve(int entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtag(entityTag);
CheckConditionalRetrieveWithValidatedEtag(validEtag);
}
public void CheckConditionalRetrieve(long entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtag(entityTag);
CheckConditionalRetrieveWithValidatedEtag(validEtag);
}
public void CheckConditionalRetrieve(Guid entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtag(entityTag);
CheckConditionalRetrieveWithValidatedEtag(validEtag);
}
public void CheckConditionalRetrieve(DateTime lastModified)
{
if (!string.Equals(this.Method, IncomingWebRequestContext.HttpGetMethod, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(this.Method, IncomingWebRequestContext.HttpHeadMethod, StringComparison.OrdinalIgnoreCase))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR2.GetString(SR2.ConditionalRetrieveGetAndHeadOnly, this.Method)));
}
DateTime? ifModifiedSince = this.IfModifiedSince;
if (ifModifiedSince.HasValue)
{
long ticksDifference = lastModified.ToUniversalTime().Ticks - ifModifiedSince.Value.ToUniversalTime().Ticks;
if (ticksDifference < TimeSpan.TicksPerSecond)
{
WebOperationContext.Current.OutgoingResponse.LastModified = lastModified;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WebFaultException(HttpStatusCode.NotModified));
}
}
}
public void CheckConditionalUpdate(string entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtagFromString(entityTag);
CheckConditionalUpdateWithValidatedEtag(validEtag);
}
public void CheckConditionalUpdate(int entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtag(entityTag);
CheckConditionalUpdateWithValidatedEtag(validEtag);
}
public void CheckConditionalUpdate(long entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtag(entityTag);
CheckConditionalUpdateWithValidatedEtag(validEtag);
}
public void CheckConditionalUpdate(Guid entityTag)
{
string validEtag = OutgoingWebResponseContext.GenerateValidEtag(entityTag);
CheckConditionalUpdateWithValidatedEtag(validEtag);
}
public Collection<ContentType> GetAcceptHeaderElements()
{
string acceptHeader = this.Accept;
if (cachedAcceptHeaderElements == null ||
(!string.Equals(acceptHeaderWhenHeaderElementsCached, acceptHeader, StringComparison.OrdinalIgnoreCase)))
{
if (string.IsNullOrEmpty(acceptHeader))
{
cachedAcceptHeaderElements = new Collection<ContentType>();
acceptHeaderWhenHeaderElementsCached = acceptHeader;
}
else
{
List<ContentType> contentTypeList = new List<ContentType>();
int offset = 0;
while (true)
{
string nextItem = Utility.QuoteAwareSubString(acceptHeader, ref offset);
if (nextItem == null)
{
break;
}
ContentType contentType = Utility.GetContentTypeOrNull(nextItem);
if (contentType != null)
{
contentTypeList.Add(contentType);
}
}
contentTypeList.Sort(new AcceptHeaderElementComparer());
cachedAcceptHeaderElements = new Collection<ContentType>(contentTypeList);
acceptHeaderWhenHeaderElementsCached = acceptHeader;
}
}
return cachedAcceptHeaderElements;
}
HttpRequestMessageProperty EnsureMessageProperty()
{
if (this.MessageProperty == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR2.GetString(SR2.HttpContextNoIncomingMessageProperty, typeof(HttpRequestMessageProperty).Name)));
}
return this.MessageProperty;
}
void CheckConditionalRetrieveWithValidatedEtag(string entityTag)
{
if (!string.Equals(this.Method, IncomingWebRequestContext.HttpGetMethod, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(this.Method, IncomingWebRequestContext.HttpHeadMethod, StringComparison.OrdinalIgnoreCase))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR2.GetString(SR2.ConditionalRetrieveGetAndHeadOnly, this.Method)));
}
if (!string.IsNullOrEmpty(entityTag))
{
string entityTagHeader = this.Headers[HttpRequestHeader.IfNoneMatch];
if (!string.IsNullOrEmpty(entityTagHeader))
{
if (IsWildCardCharacter(entityTagHeader) ||
DoesHeaderContainEtag(entityTagHeader, entityTag))
{
// set response entityTag directly because it has already been validated
WebOperationContext.Current.OutgoingResponse.ETag = entityTag;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WebFaultException(HttpStatusCode.NotModified));
}
}
}
}
void CheckConditionalUpdateWithValidatedEtag(string entityTag)
{
bool isPutMethod = string.Equals(this.Method, IncomingWebRequestContext.HttpPutMethod, StringComparison.OrdinalIgnoreCase);
if (!isPutMethod &&
!string.Equals(this.Method, IncomingWebRequestContext.HttpPostMethod, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(this.Method, IncomingWebRequestContext.HttpDeleteMethod, StringComparison.OrdinalIgnoreCase))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR2.GetString(SR2.ConditionalUpdatePutPostAndDeleteOnly, this.Method)));
}
string headerOfInterest;
// if the current entityTag is null then the resource doesn't currently exist and the
// a PUT request should only succeed if If-None-Match equals '*'.
if (isPutMethod && string.IsNullOrEmpty(entityTag))
{
headerOfInterest = this.Headers[HttpRequestHeader.IfNoneMatch];
if (string.IsNullOrEmpty(headerOfInterest) ||
!IsWildCardCharacter(headerOfInterest))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WebFaultException(HttpStatusCode.PreconditionFailed));
}
}
else
{
// all remaining cases are with an If-Match header
headerOfInterest = this.Headers[HttpRequestHeader.IfMatch];
if (string.IsNullOrEmpty(headerOfInterest) ||
(!IsWildCardCharacter(headerOfInterest) &&
!DoesHeaderContainEtag(headerOfInterest, entityTag)))
{
// set response entityTag directly because it has already been validated
WebOperationContext.Current.OutgoingResponse.ETag = entityTag;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WebFaultException(HttpStatusCode.PreconditionFailed));
}
}
}
static bool DoesHeaderContainEtag(string header, string entityTag)
{
int offset = 0;
while (true)
{
string nextEntityTag = Utility.QuoteAwareSubString(header, ref offset);
if (nextEntityTag == null)
{
break;
}
if (string.Equals(nextEntityTag, entityTag, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
static bool IsWildCardCharacter(string header)
{
return (header.Trim() == "*");
}
}
class AcceptHeaderElementComparer : IComparer<ContentType>
{
static NumberStyles numberStyles = NumberStyles.AllowDecimalPoint;
public int Compare(ContentType x, ContentType y)
{
string[] xTypeSubType = x.MediaType.Split('/');
string[] yTypeSubType = y.MediaType.Split('/');
Fx.Assert(xTypeSubType.Length == 2, "The creation of the ContentType would have failed if there wasn't a type and subtype.");
Fx.Assert(yTypeSubType.Length == 2, "The creation of the ContentType would have failed if there wasn't a type and subtype.");
if (string.Equals(xTypeSubType[0], yTypeSubType[0], StringComparison.OrdinalIgnoreCase))
{
if (string.Equals(xTypeSubType[1], yTypeSubType[1], StringComparison.OrdinalIgnoreCase))
{
// need to check the number of parameters to determine which is more specific
bool xHasParam = HasParameters(x);
bool yHasParam = HasParameters(y);
if (xHasParam && !yHasParam)
{
return 1;
}
else if (!xHasParam && yHasParam)
{
return -1;
}
}
else
{
if (xTypeSubType[1][0] == '*' && xTypeSubType[1].Length == 1)
{
return 1;
}
if (yTypeSubType[1][0] == '*' && yTypeSubType[1].Length == 1)
{
return -1;
}
}
}
else if (xTypeSubType[0][0] == '*' && xTypeSubType[0].Length == 1)
{
return 1;
}
else if (yTypeSubType[0][0] == '*' && yTypeSubType[0].Length == 1)
{
return -1;
}
decimal qualityDifference = GetQualityFactor(x) - GetQualityFactor(y);
if (qualityDifference < 0)
{
return 1;
}
else if (qualityDifference > 0)
{
return -1;
}
return 0;
}
decimal GetQualityFactor(ContentType contentType)
{
decimal result;
foreach (string key in contentType.Parameters.Keys)
{
if (string.Equals("q", key, StringComparison.OrdinalIgnoreCase))
{
if (decimal.TryParse(contentType.Parameters[key], numberStyles, CultureInfo.InvariantCulture, out result) &&
(result <= (decimal)1.0))
{
return result;
}
}
}
return (decimal)1.0;
}
bool HasParameters(ContentType contentType)
{
int number = 0;
foreach (string param in contentType.Parameters.Keys)
{
if (!string.Equals("q", param, StringComparison.OrdinalIgnoreCase))
{
number++;
}
}
return (number > 0);
}
}
}
|