2 // System.Net.WebHeaderCollection
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Miguel de Icaza (miguel@novell.com)
9 // Copyright 2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright 2007 Novell, Inc. (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Runtime.InteropServices;
38 using System.Runtime.Serialization;
41 // See RFC 2068 par 4.2 Message Headers
47 public class WebHeaderCollection : NameValueCollection, ISerializable
49 private static readonly Hashtable restricted;
50 private static readonly Hashtable multiValue;
51 private bool internallyCreated = false;
55 static WebHeaderCollection ()
57 // the list of restricted header names as defined
59 restricted = new Hashtable (CaseInsensitiveHashCodeProvider.DefaultInvariant,
60 CaseInsensitiveComparer.DefaultInvariant);
62 restricted.Add ("accept", true);
63 restricted.Add ("connection", true);
64 restricted.Add ("content-length", true);
65 restricted.Add ("content-type", true);
66 restricted.Add ("date", true);
67 restricted.Add ("expect", true);
68 restricted.Add ("host", true);
69 restricted.Add ("if-modified-since", true);
70 restricted.Add ("range", true);
71 restricted.Add ("referer", true);
72 restricted.Add ("transfer-encoding", true);
73 restricted.Add ("user-agent", true);
75 // see par 14 of RFC 2068 to see which header names
76 // accept multiple values each separated by a comma
77 multiValue = new Hashtable (CaseInsensitiveHashCodeProvider.DefaultInvariant,
78 CaseInsensitiveComparer.DefaultInvariant);
80 multiValue.Add ("accept", true);
81 multiValue.Add ("accept-charset", true);
82 multiValue.Add ("accept-encoding", true);
83 multiValue.Add ("accept-language", true);
84 multiValue.Add ("accept-ranges", true);
85 multiValue.Add ("allow", true);
86 multiValue.Add ("authorization", true);
87 multiValue.Add ("cache-control", true);
88 multiValue.Add ("connection", true);
89 multiValue.Add ("content-encoding", true);
90 multiValue.Add ("content-language", true);
91 multiValue.Add ("expect", true);
92 multiValue.Add ("if-match", true);
93 multiValue.Add ("if-none-match", true);
94 multiValue.Add ("proxy-authenticate", true);
95 multiValue.Add ("public", true);
96 multiValue.Add ("range", true);
97 multiValue.Add ("transfer-encoding", true);
98 multiValue.Add ("upgrade", true);
99 multiValue.Add ("vary", true);
100 multiValue.Add ("via", true);
101 multiValue.Add ("warning", true);
102 multiValue.Add ("www-authenticate", true);
105 multiValue.Add ("set-cookie", true);
106 multiValue.Add ("set-cookie2", true);
111 public WebHeaderCollection () { }
113 protected WebHeaderCollection (SerializationInfo serializationInfo,
114 StreamingContext streamingContext)
119 count = serializationInfo.GetInt32("Count");
120 for (int i = 0; i < count; i++)
121 this.Add (serializationInfo.GetString (i.ToString ()),
122 serializationInfo.GetString ((count + i).ToString ()));
123 } catch (SerializationException){
124 count = serializationInfo.GetInt32("count");
125 for (int i = 0; i < count; i++)
126 this.Add (serializationInfo.GetString ("k" + i),
127 serializationInfo.GetString ("v" + i));
132 internal WebHeaderCollection (bool internallyCreated)
134 this.internallyCreated = internallyCreated;
139 public void Add (string header)
142 throw new ArgumentNullException ("header");
143 int pos = header.IndexOf (':');
145 throw new ArgumentException ("no colon found", "header");
146 this.Add (header.Substring (0, pos),
147 header.Substring (pos + 1));
150 public override void Add (string name, string value)
153 throw new ArgumentNullException ("name");
154 if (internallyCreated && IsRestricted (name))
155 throw new ArgumentException ("This header must be modified with the appropiate property.");
156 this.AddWithoutValidate (name, value);
159 protected void AddWithoutValidate (string headerName, string headerValue)
161 if (!IsHeaderName (headerName))
162 throw new ArgumentException ("invalid header name: " + headerName, "headerName");
163 if (headerValue == null)
164 headerValue = String.Empty;
166 headerValue = headerValue.Trim ();
167 if (!IsHeaderValue (headerValue))
168 throw new ArgumentException ("invalid header value: " + headerValue, "headerValue");
169 base.Add (headerName, headerValue);
172 public override string [] GetValues (string header)
175 throw new ArgumentNullException ("header");
177 string [] values = base.GetValues (header);
178 if (values == null || values.Length == 0)
182 if (IsMultiValue (header)) {
183 values = GetMultipleValues (values);
190 public override string[] GetValues (int index)
192 string[] values = base.GetValues (index);
193 if (values == null || values.Length == 0) {
200 /* Now i wonder why this is here...
201 static string [] GetMultipleValues (string [] values)
203 ArrayList mvalues = new ArrayList (values.Length);
204 StringBuilder sb = null;
205 for (int i = 0; i < values.Length; ++i) {
206 string val = values [i];
207 if (val.IndexOf (',') == -1) {
213 sb = new StringBuilder ();
216 for (int k = 0; k < val.Length; k++) {
220 } else if (!quote && c == ',') {
221 mvalues.Add (sb.ToString ().Trim ());
229 mvalues.Add (sb.ToString ().Trim ());
234 return (string []) mvalues.ToArray (typeof (string));
238 public static bool IsRestricted (string headerName)
240 if (headerName == null)
241 throw new ArgumentNullException ("headerName");
243 if (headerName == "") // MS throw nullexception here!
244 throw new ArgumentException ("empty string", "headerName");
246 return restricted.ContainsKey (headerName);
250 [MonoNotSupported("")]
251 public static bool IsRestricted (string headerName, bool response)
253 throw new NotImplementedException ();
257 public override void OnDeserialization (object sender)
261 public override void Remove (string name)
264 throw new ArgumentNullException ("name");
265 if (internallyCreated && IsRestricted (name))
266 throw new ArgumentException ("restricted header");
270 public override void Set (string name, string value)
273 throw new ArgumentNullException ("name");
274 if (internallyCreated && IsRestricted (name))
275 throw new ArgumentException ("restricted header");
276 if (!IsHeaderName (name))
277 throw new ArgumentException ("invalid header name");
279 value = String.Empty;
281 value = value.Trim ();
282 if (!IsHeaderValue (value))
283 throw new ArgumentException ("invalid header value");
284 base.Set (name, value);
287 public byte[] ToByteArray ()
289 return Encoding.UTF8.GetBytes(ToString ());
292 public override string ToString ()
294 StringBuilder sb = new StringBuilder();
296 int count = base.Count;
297 for (int i = 0; i < count ; i++)
298 sb.Append (GetKey (i))
303 return sb.Append("\r\n").ToString();
306 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
307 StreamingContext streamingContext)
309 GetObjectData (serializationInfo, streamingContext);
312 public override void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
314 int count = base.Count;
315 serializationInfo.AddValue ("Count", count);
316 for (int i = 0; i < count; i++) {
317 serializationInfo.AddValue (i.ToString (), GetKey (i));
318 serializationInfo.AddValue ((count + i).ToString (), Get (i));
322 public override string[] AllKeys
325 return(base.AllKeys);
329 public override int Count
336 public override KeysCollection Keys
343 public override string Get (int index)
345 return(base.Get (index));
348 public override string Get (string name)
350 return(base.Get (name));
353 public override string GetKey (int index)
355 return(base.GetKey (index));
359 public void Add (HttpRequestHeader header, string value)
361 Add (RequestHeaderToString (header), value);
364 public void Remove (HttpRequestHeader header)
366 Remove (RequestHeaderToString (header));
369 public void Set (HttpRequestHeader header, string value)
371 Set (RequestHeaderToString (header), value);
374 public void Add (HttpResponseHeader header, string value)
376 Add (ResponseHeaderToString (header), value);
379 public void Remove (HttpResponseHeader header)
381 Remove (ResponseHeaderToString (header));
384 public void Set (HttpResponseHeader header, string value)
386 Set (ResponseHeaderToString (header), value);
389 string RequestHeaderToString (HttpRequestHeader value)
392 case HttpRequestHeader.CacheControl:
393 return "cache-control";
394 case HttpRequestHeader.Connection:
396 case HttpRequestHeader.Date:
398 case HttpRequestHeader.KeepAlive:
400 case HttpRequestHeader.Pragma:
402 case HttpRequestHeader.Trailer:
404 case HttpRequestHeader.TransferEncoding:
405 return "transfer-encoding";
406 case HttpRequestHeader.Upgrade:
408 case HttpRequestHeader.Via:
410 case HttpRequestHeader.Warning:
412 case HttpRequestHeader.Allow:
414 case HttpRequestHeader.ContentLength:
415 return "content-length";
416 case HttpRequestHeader.ContentType:
417 return "content-type";
418 case HttpRequestHeader.ContentEncoding:
419 return "content-encoding";
420 case HttpRequestHeader.ContentLanguage:
421 return "content-language";
422 case HttpRequestHeader.ContentLocation:
423 return "content-location";
424 case HttpRequestHeader.ContentMd5:
425 return "content-md5";
426 case HttpRequestHeader.ContentRange:
427 return "content-range";
428 case HttpRequestHeader.Expires:
430 case HttpRequestHeader.LastModified:
431 return "last-modified";
432 case HttpRequestHeader.Accept:
434 case HttpRequestHeader.AcceptCharset:
435 return "accept-charset";
436 case HttpRequestHeader.AcceptEncoding:
437 return "accept-encoding";
438 case HttpRequestHeader.AcceptLanguage:
439 return "accept-language";
440 case HttpRequestHeader.Authorization:
441 return "authorization";
442 case HttpRequestHeader.Cookie:
444 case HttpRequestHeader.Expect:
446 case HttpRequestHeader.From:
448 case HttpRequestHeader.Host:
450 case HttpRequestHeader.IfMatch:
452 case HttpRequestHeader.IfModifiedSince:
453 return "if-modified-since";
454 case HttpRequestHeader.IfNoneMatch:
455 return "if-none-match";
456 case HttpRequestHeader.IfRange:
458 case HttpRequestHeader.IfUnmodifiedSince:
459 return "if-unmodified-since";
460 case HttpRequestHeader.MaxForwards:
461 return "max-forwards";
462 case HttpRequestHeader.ProxyAuthorization:
463 return "proxy-authorization";
464 case HttpRequestHeader.Referer:
466 case HttpRequestHeader.Range:
468 case HttpRequestHeader.Te:
470 case HttpRequestHeader.Translate:
472 case HttpRequestHeader.UserAgent:
475 throw new InvalidOperationException ();
480 public string this[HttpRequestHeader hrh]
483 return Get (RequestHeaderToString (hrh));
487 Add (RequestHeaderToString (hrh), value);
491 string ResponseHeaderToString (HttpResponseHeader value)
494 case HttpResponseHeader.CacheControl:
495 return "cache-control";
496 case HttpResponseHeader.Connection:
498 case HttpResponseHeader.Date:
500 case HttpResponseHeader.KeepAlive:
502 case HttpResponseHeader.Pragma:
504 case HttpResponseHeader.Trailer:
506 case HttpResponseHeader.TransferEncoding:
507 return "transfer-encoding";
508 case HttpResponseHeader.Upgrade:
510 case HttpResponseHeader.Via:
512 case HttpResponseHeader.Warning:
514 case HttpResponseHeader.Allow:
516 case HttpResponseHeader.ContentLength:
517 return "content-length";
518 case HttpResponseHeader.ContentType:
519 return "content-type";
520 case HttpResponseHeader.ContentEncoding:
521 return "content-encoding";
522 case HttpResponseHeader.ContentLanguage:
523 return "content-language";
524 case HttpResponseHeader.ContentLocation:
525 return "content-location";
526 case HttpResponseHeader.ContentMd5:
527 return "content-md5";
528 case HttpResponseHeader.ContentRange:
529 return "content-range";
530 case HttpResponseHeader.Expires:
532 case HttpResponseHeader.LastModified:
533 return "last-modified";
534 case HttpResponseHeader.AcceptRanges:
535 return "accept-ranges";
536 case HttpResponseHeader.Age:
538 case HttpResponseHeader.ETag:
540 case HttpResponseHeader.Location:
542 case HttpResponseHeader.ProxyAuthenticate:
543 return "proxy-authenticate";
544 case HttpResponseHeader.RetryAfter:
546 case HttpResponseHeader.Server:
548 case HttpResponseHeader.SetCookie:
550 case HttpResponseHeader.Vary:
552 case HttpResponseHeader.WwwAuthenticate:
553 return "www-authenticate";
555 throw new InvalidOperationException ();
558 public string this[HttpResponseHeader hrh]
562 return Get (ResponseHeaderToString (hrh));
567 Add (ResponseHeaderToString (hrh), value);
571 public override void Clear ()
577 public override IEnumerator GetEnumerator ()
579 return(base.GetEnumerator ());
585 // With this we don't check for invalid characters in header. See bug #55994.
586 internal void SetInternal (string header)
588 int pos = header.IndexOf (':');
590 throw new ArgumentException ("no colon found", "header");
592 SetInternal (header.Substring (0, pos), header.Substring (pos + 1));
595 internal void SetInternal (string name, string value)
598 value = String.Empty;
600 value = value.Trim ();
601 if (!IsHeaderValue (value))
602 throw new ArgumentException ("invalid header value");
604 if (IsMultiValue (name)) {
605 base.Add (name, value);
608 base.Set (name, value);
612 internal void RemoveAndAdd (string name, string value)
615 value = String.Empty;
617 value = value.Trim ();
620 base.Set (name, value);
623 internal void RemoveInternal (string name)
626 throw new ArgumentNullException ("name");
632 internal static bool IsMultiValue (string headerName)
634 if (headerName == null || headerName == "")
637 return multiValue.ContainsKey (headerName);
640 internal static bool IsHeaderValue (string value)
642 // TEXT any 8 bit value except CTL's (0-31 and 127)
643 // but including \r\n space and \t
644 // after a newline at least one space or \t must follow
645 // certain header fields allow comments ()
647 int len = value.Length;
648 for (int i = 0; i < len; i++) {
652 if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
654 if (c == '\n' && ++i < len) {
656 if (c != ' ' && c != '\t')
664 internal static bool IsHeaderName (string name)
666 // token = 1*<any CHAR except CTLs or tspecials>
667 // tspecials = "(" | ")" | "<" | ">" | "@"
668 // | "," | ";" | ":" | "\" | <">
669 // | "/" | "[" | "]" | "?" | "="
670 // | "{" | "}" | SP | HT
672 if (name == null || name.Length == 0)
675 int len = name.Length;
676 for (int i = 0; i < len; i++) {
678 if (c < 0x20 || c >= 0x7f)
682 return name.IndexOfAny (tspecials) == -1;
685 private static char [] tspecials =
686 new char [] {'(', ')', '<', '>', '@',
687 ',', ';', ':', '\\', '"',
688 '/', '[', ']', '?', '=',
689 '{', '}', ' ', '\t'};