forked from OpenDataSpace/chemistry-dotcmis
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.cs
1037 lines (935 loc) · 36.8 KB
/
http.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Runtime.Serialization;
using DotCMIS.Enums;
using DotCMIS.Exceptions;
using DotCMIS.Util;
using log4net;
namespace DotCMIS.Binding
{
public class HttpWebRequestResource : IDisposable
{
private static object ResourceLock = new object();
private static HashSet<HttpWebRequest> ResourceSet = new HashSet<HttpWebRequest>();
private HttpWebRequest Request;
public static void AbortAll()
{
lock (ResourceLock) {
foreach (HttpWebRequest request in ResourceSet) {
request.Abort ();
}
}
}
public HttpWebRequestResource()
{
Request = null;
}
public void StartResource(HttpWebRequest request)
{
lock (ResourceLock) {
if (Request != null) {
ResourceSet.Remove (Request);
}
Request = request;
ResourceSet.Add (Request);
}
}
public void Dispose()
{
if (Request != null) {
lock (ResourceLock) {
ResourceSet.Remove (Request);
}
}
}
}
}
namespace DotCMIS.Binding.Impl
{
internal static class HttpUtils
{
// Log.
private static readonly ILog Logger = LogManager.GetLogger(typeof(HttpUtils));
public delegate void Output(Stream stream);
public static Response InvokeGET(UrlBuilder url, BindingSession session, bool outputErrors)
{
return Invoke(url, "GET", null, null, session, null, null, null, outputErrors);
}
public static Response InvokeGET(UrlBuilder url, BindingSession session, long? offset, long? length, bool outputErrors)
{
return Invoke(url, "GET", null, null, session, offset, length, null, outputErrors);
}
public static Response InvokePOST(UrlBuilder url, String contentType, Output writer, BindingSession session)
{
return Invoke(url, "POST", contentType, writer, session, null, null, null, true);
}
public static Response InvokePUT(UrlBuilder url, String contentType, IDictionary<string, string> headers, Output writer, BindingSession session)
{
return Invoke(url, "PUT", contentType, writer, session, null, null, headers, true);
}
public static Response InvokeDELETE(UrlBuilder url, BindingSession session)
{
return Invoke(url, "DELETE", null, null, session, null, null, null, true);
}
private static Response Invoke(UrlBuilder url, String method, String contentType, Output writer, BindingSession session,
long? offset, long? length, IDictionary<string, string> headers, bool outputErrors)
{
Guid tag = Guid.NewGuid();
string request = method + " " + url;
Stopwatch watch = new Stopwatch();
watch.Start();
using (HttpWebRequestResource resource = new HttpWebRequestResource ())
{
try
{
// log before connect
Trace.WriteLineIf(DotCMISDebug.DotCMISSwitch.TraceInfo, string.Format("[{0}] starting {1}", tag.ToString(), request));
//Handles infrequent networking conditions
int retry = 0;
for(;;){
// create connection
HttpWebRequest conn = (HttpWebRequest)WebRequest.Create(url.Url);
conn.Method = method;
resource.StartResource(conn);
// device management
string deviceIdentifier = session.GetValue(SessionParameter.DeviceIdentifier) as String;
if(deviceIdentifier != null)
{
conn.Headers.Add("Device-ID", deviceIdentifier);
}
// user agent
string userAgent = session.GetValue(SessionParameter.UserAgent) as String;
conn.UserAgent = userAgent == null ? "Apache Chemistry DotCMIS" : userAgent;
// timeouts
int connectTimeout = session.GetValue(SessionParameter.ConnectTimeout, -2);
if (connectTimeout >= -1)
{
conn.Timeout = connectTimeout;
}
int readTimeout = session.GetValue(SessionParameter.ReadTimeout, -2);
if (readTimeout >= -1)
{
conn.ReadWriteTimeout = readTimeout;
}
// set content type
if (contentType != null)
{
conn.ContentType = contentType;
}
// set additional headers
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
conn.Headers.Add(header.Key, header.Value);
}
}
// authenticate
IAuthenticationProvider authProvider = session.GetAuthenticationProvider();
if (authProvider != null)
{
conn.PreAuthenticate = true;
authProvider.Authenticate(conn);
}
// range
if (offset != null && length != null)
{
if (offset < Int32.MaxValue && offset + length - 1 < Int32.MaxValue)
{
conn.AddRange((int)offset, (int)offset + (int)length - 1);
}
else
{
try
{
MethodInfo mi = conn.GetType().GetMethod("AddRange", new Type[] { typeof(Int64), typeof(Int64) });
mi.Invoke(conn, new object[] { offset, offset + length - 1 });
}
catch (Exception e)
{
throw new CmisInvalidArgumentException("Offset or length too big!", e);
}
}
}
else if (offset != null)
{
if (offset < Int32.MaxValue)
{
conn.AddRange((int)offset);
}
else
{
try
{
MethodInfo mi = conn.GetType().GetMethod("AddRange", new Type[] { typeof(Int64) });
mi.Invoke(conn, new object[] { offset });
}
catch (Exception e)
{
throw new CmisInvalidArgumentException("Offset too big!", e);
}
}
}
// compression
string compressionFlag = session.GetValue(SessionParameter.Compression) as string;
if (compressionFlag != null && compressionFlag.ToLower().Equals("true"))
{
conn.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
// send data
if (writer != null)
{
#if __MonoCS__ // Unchunked upload for Mono, because of Mono bug 21135
// First write request to temporary file, inefficient but easier than rewriting large parts of DotCMIS
string tempFile = System.IO.Path.GetTempFileName();
// Make the temporary file readable only by the user, since data might be confidential.
Mono.Unix.Native.Syscall.chmod(tempFile,
Mono.Unix.Native.FilePermissions.S_IWUSR | Mono.Unix.Native.FilePermissions.S_IRUSR);
using (var tempStream = new StreamWriter(tempFile))
{
writer(tempStream.BaseStream);
}
// Send the request to the server
FileStream tempFileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read);
conn.ContentLength = tempFileStream.Length;
Stream requestStream = conn.GetRequestStream();
tempFileStream.CopyTo(requestStream);
requestStream.Close();
// Remove temporary file
tempFileStream.Close();
File.Delete(tempFile);
#else
conn.SendChunked = true;
Stream requestStream = conn.GetRequestStream();
writer(requestStream);
requestStream.Close();
#endif
}
else
{
#if __MonoCS__
//around for MONO HTTP DELETE issue
//http://stackoverflow.com/questions/11785597/monotouch-iphone-call-to-httpwebrequest-getrequeststream-connects-to-server
if (method == "DELETE")
{
conn.ContentLength = 0;
Stream requestStream = conn.GetRequestStream();
requestStream.Close();
}
#endif
}
// connect
try
{
Logger.Debug("About to call conn.GetResponse() with HttpWebRequest.Timeout=" + conn.Timeout + "ms and HttpWebRequest.ReadWriteTimeout=" + conn.ReadWriteTimeout + "ms");
HttpWebResponse response = (HttpWebResponse)conn.GetResponse();
Logger.Debug("conn.GetResponse() result: " + response);
if (authProvider != null)
{
authProvider.HandleResponse(response);
}
watch.Stop();
Trace.WriteLineIf(DotCMISDebug.DotCMISSwitch.TraceInfo, string.Format("[{0}] received response after {1} ms", tag.ToString(), watch.ElapsedMilliseconds.ToString()));
return new Response(response);
}
catch (WebException we)
{
Logger.Debug("conn.GetResponse() triggered exception: " + we);
if (method != "GET" || !ExceptionFixabilityDecider.CanExceptionBeFixedByRetry(we) || retry == 5) {
watch.Stop();
if (outputErrors)
{
Logger.Debug(method + " request failed: " + url + " " + we.Message + " " + we.Status);
}
Trace.WriteLineIf(DotCMISDebug.DotCMISSwitch.TraceInfo, string.Format("[{0}] received response after {1} ms", tag.ToString(), watch.ElapsedMilliseconds.ToString()));
if (we.Status.Equals(WebExceptionStatus.ConnectFailure))
{
Logger.Error("Your CMIS server is unreachable. Please check the server and network/firewalls. "
+ " How to test the connection: On the same computer as CmisSync, launch Firefox at "
+ url + " and enter your username/password. If the connection is successful an Atom XML file gets downloaded, "
+ "if not please repair your server or network.");
return null;
}
else
{
return new Response(we);
}
}
retry++;
watch.Stop();
Thread.Sleep(50);
watch.Start();
Trace.WriteLineIf(DotCMISDebug.DotCMISSwitch.TraceInfo, string.Format("[{0}] {1} retry No {2}", tag.ToString(), we.Message, retry.ToString()));
}
}
}
catch (Exception e)
{
watch.Stop();
Trace.WriteLineIf(DotCMISDebug.DotCMISSwitch.TraceInfo, string.Format("[{0}] Cannot access {1}: {2} after {3} ms", tag.ToString(), request, e.Message, watch.ElapsedMilliseconds));
throw new CmisConnectionException("Cannot access " + url + ": " + e.Message, e);
}
}
}
internal class Response
{
private readonly WebResponse response;
public HttpStatusCode StatusCode { get; private set; }
public string Message { get; private set; }
public Stream Stream { get; private set; }
public string ErrorContent { get; private set; }
public string ContentType { get; private set; }
public long? ContentLength { get; private set; }
public Dictionary<string, string[]> Headers { get; private set; }
public Response(HttpWebResponse httpResponse)
{
this.response = httpResponse;
this.ExtractHeader();
StatusCode = httpResponse.StatusCode;
Message = httpResponse.StatusDescription;
ContentType = httpResponse.ContentType;
ContentLength = httpResponse.ContentLength == -1 ? null : (long?)httpResponse.ContentLength;
string contentTransferEncoding = httpResponse.Headers["Content-Transfer-Encoding"];
bool isBase64 = contentTransferEncoding != null && contentTransferEncoding.Equals("base64", StringComparison.CurrentCultureIgnoreCase);
Headers = new Dictionary<string,string[]>();
foreach (string key in httpResponse.Headers.AllKeys)
{
string[] values = httpResponse.Headers.GetValues(key);
Headers.Add(key, values);
}
if (httpResponse.StatusCode == HttpStatusCode.OK ||
httpResponse.StatusCode == HttpStatusCode.Created ||
httpResponse.StatusCode == HttpStatusCode.NonAuthoritativeInformation ||
httpResponse.StatusCode == HttpStatusCode.PartialContent)
{
if (isBase64)
{
Stream = new BufferedStream(new CryptoStream(httpResponse.GetResponseStream(), new FromBase64Transform(), CryptoStreamMode.Read), 64 * 1024);
}
else
{
Stream = new BufferedStream(httpResponse.GetResponseStream(), 64 * 1024);
}
}
else
{
try { httpResponse.Close(); }
catch (Exception) { }
}
}
public Response(WebException exception)
{
response = exception.Response;
this.ExtractHeader();
HttpWebResponse httpResponse = response as HttpWebResponse;
if (httpResponse != null)
{
StatusCode = httpResponse.StatusCode;
Message = httpResponse.StatusDescription;
ContentType = httpResponse.ContentType;
if (ContentType != null && ContentType.ToLower().StartsWith("text/"))
{
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(httpResponse.GetResponseStream()))
{
string s;
while ((s = sr.ReadLine()) != null)
{
sb.Append(s);
sb.Append('\n');
}
}
ErrorContent = sb.ToString();
}
}
else
{
StatusCode = HttpStatusCode.InternalServerError;
Message = exception.Status.ToString();
}
try { response.Close(); }
catch (Exception) { }
}
public void CloseStream()
{
if (Stream != null)
{
Stream.Close();
}
}
private void ExtractHeader() {
this.Headers = new Dictionary<string, string[]>();
// Null checks
if (null == this.response)
{
Logger.Error("response is null");
return;
}
if (null == this.response.Headers)
{
Logger.Error("response.Headers is null");
return;
}
// Copy headers.
for (int i = 0; i < this.response.Headers.Count; ++i)
{
this.Headers.Add(this.response.Headers.GetKey(i), this.response.Headers.GetValues(i));
}
}
}
}
public static class ExceptionFixabilityDecider {
public static bool CanExceptionBeFixedByRetry(WebException we)
{
if(!(we.Response is HttpWebResponse)){
return true;
}
return CanExceptionStatusCodeBeFixedByRetry((we.Response as HttpWebResponse).StatusCode);
}
public static bool CanExceptionStatusCodeBeFixedByRetry(HttpStatusCode code)
{
if(code == HttpStatusCode.NotFound || code == HttpStatusCode.Forbidden) {
return false;
}
return true;
}
}
internal class UrlBuilder
{
private UriBuilder uri;
public Uri Url
{
get { return uri.Uri; }
}
public UrlBuilder(string url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
uri = new UriBuilder(url);
}
public UrlBuilder AddPath(string path)
{
if (path == null || path.Length == 0)
{
return this;
}
uri.Path = uri.Path.TrimEnd('/', '\\');
path = path.TrimStart('/', '\\');
uri.Path = uri.Path + "/" + path;
return this;
}
public UrlBuilder AddParameter(string name, object value)
{
if ((name == null) || (value == null))
{
return this;
}
string valueStr = Uri.EscapeDataString(UrlBuilder.NormalizeParameter(value));
if (uri.Query != null && uri.Query.Length > 1)
{
uri.Query = uri.Query.Substring(1) + "&" + name + "=" + valueStr;
}
else
{
uri.Query = name + "=" + valueStr;
}
return this;
}
public static string NormalizeParameter(object value)
{
if (value == null)
{
return null;
}
else if (value is Enum)
{
return ((Enum)value).GetCmisValue();
}
else if (value is bool)
{
return (bool)value ? "true" : "false";
}
return value.ToString();
}
public override string ToString()
{
return Url.ToString();
}
}
internal class UrlParser
{
private Uri uri;
public UrlParser(string url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
uri = new Uri(url);
}
public string GetQueryValue(string name)
{
string query = uri.Query;
if (!query.Contains("?"))
{
return null;
}
query = query.Substring(query.IndexOf('?') + 1);
foreach (string segment in query.Split('&'))
{
string[] parts = segment.Split('=');
if(parts[0] != name)
{
continue;
}
if (parts.Length == 1)
{
return string.Empty;
}
if (parts.Length == 2)
{
return Uri.UnescapeDataString(parts[1]);
}
return null;
}
return null;
}
}
internal class MimeHelper
{
public const string ContentDisposition = "Content-Disposition";
public const string DispositionAttachment = "attachment";
public const string DispositionFilename = "filename";
public const string DispositionName = "name";
public const string DispositionFormDataContent = "form-data; " + DispositionName + "=\"content\"";
private const string MIMESpecials = "()<>@,;:\\\"/[]?=" + "\t ";
private const string RFC2231Specials = "*'%" + MIMESpecials;
private static char[] HexDigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static byte[] HexDecode = new byte[0x80];
public static string EncodeContentDisposition(string disposition, string filename)
{
if (disposition == null)
{
disposition = DispositionAttachment;
}
return disposition + EncodeRFC2231(DispositionFilename, filename);
}
protected static string EncodeRFC2231(string key, string value)
{
StringBuilder buf = new StringBuilder();
bool encoded = EncodeRFC2231value(value, buf);
if (encoded)
{
return "; " + key + "*=" + buf.ToString();
}
else
{
return "; " + key + "=" + value;
}
}
protected static bool EncodeRFC2231value(string value, StringBuilder buf)
{
buf.Append("UTF-8");
buf.Append("''"); // no language
byte[] bytes;
try
{
bytes = UTF8Encoding.UTF8.GetBytes(value);
}
catch (Exception)
{
return true;
}
bool encoded = false;
for (int i = 0; i < bytes.Length; i++)
{
int ch = bytes[i] & 0xff;
if (ch <= 32 || ch >= 127 || RFC2231Specials.IndexOf((char)ch) != -1)
{
buf.Append('%');
buf.Append(HexDigits[ch >> 4]);
buf.Append(HexDigits[ch & 0xf]);
encoded = true;
}
else
{
buf.Append((char)ch);
}
}
return encoded;
}
protected static string DecodeRFC2231value(string value)
{
int q1 = value.IndexOf('\'');
if (q1 == -1)
{
return value;
}
string mimeCharset = value.Substring(0, q1);
int q2 = value.IndexOf('\'', q1 + 1);
if (q2 == -1)
{
return value;
}
byte[] bytes = FromHex(value.Substring(q2 + 1));
try
{
return UTF8Encoding.UTF8.GetString(bytes);
}
catch (Exception)
{
return value;
}
}
protected static byte[] FromHex(string data)
{
using (MemoryStream stream = new MemoryStream())
{
for (int i = 0; i < HexDigits.Length; i++)
{
HexDecode[(int)HexDigits[i]] = (byte)i;
HexDecode[(int)Char.ToLower(HexDigits[i])] = (byte)i;
}
for (int i = 0; i < data.Length; )
{
char c = data[i++];
if (c == '%')
{
if (i > data.Length - 2)
{
break;
}
byte b1 = HexDecode[data[i++] & 0x7f];
byte b2 = HexDecode[data[i++] & 0x7f];
stream.WriteByte((byte)((b1 << 4) | b2));
}
else
{
stream.WriteByte((byte)c);
}
}
return stream.ToArray();
}
}
public static string DecodeContentDisposition(string value, Dictionary<string, string> parameters)
{
try
{
HeaderTokenizer tokenizer = new HeaderTokenizer(value);
Token token = tokenizer.Next();
if (token.Type != Token.Atomic)
{
return null;
}
string disposition = token.Value;
string remainder = tokenizer.Remainder;
if (remainder != null)
{
GetParameters(remainder, parameters);
}
return disposition;
}
catch (ParseException)
{
return null;
}
}
private static void GetParameters(string list, Dictionary<string, string> parameters)
{
HeaderTokenizer tokenizer = new HeaderTokenizer(list);
while (true)
{
Token token = tokenizer.Next();
switch (token.Type)
{
case Token.EOF:
return;
case ';':
token = tokenizer.Next();
if (token.Type == Token.EOF)
{
return;
}
if (token.Type != Token.Atomic)
{
throw new ParseException("Invalid parameter name: " + token.Value);
}
string name = token.Value.ToLower(new System.Globalization.CultureInfo("en"));
token = tokenizer.Next();
if (token.Type != '=')
{
throw new ParseException("Missing '='");
}
token = tokenizer.Next();
if (token.Type != Token.Atomic && token.Type != Token.QuotedString)
{
throw new ParseException("Invalid parameter value: " + token.Value);
}
string value = token.Value;
if (name.EndsWith("*"))
{
name = name.Substring(0, name.Length - 1);
value = DecodeRFC2231value(value);
}
parameters[name] = value;
break;
default:
throw new ParseException("Missing ';'");
}
}
}
[Serializable]
public class ParseException : FormatException
{
public ParseException(string message)
: base(message)
{
}
public ParseException()
{
}
public ParseException(string message, Exception inner)
: base(message, inner)
{
}
protected ParseException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
protected class Token
{
public const int Atomic = -1;
public const int QuotedString = -2;
public const int Comment = -3;
public const int EOF = -4;
public int Type { get; private set; }
public string Value { get; private set; }
public Token(int type, string value)
{
Type = type;
Value = value;
}
}
protected class HeaderTokenizer
{
private static readonly Token EOF = new Token(Token.EOF, null);
private readonly string Header;
private readonly string Delimiters;
private readonly bool SkipComments;
private int pos;
public HeaderTokenizer(string header)
: this(header, MIMESpecials, true)
{
}
protected HeaderTokenizer(string header, string delimiters, bool skipComments)
{
Header = header;
Delimiters = delimiters;
SkipComments = skipComments;
}
public string Remainder
{
get
{
if (pos >= Header.Length)
{
return null;
}
else
{
return Header.Substring(pos);
}
}
}
public Token Next()
{
return ReadToken();
}
private Token ReadToken()
{
while (pos < Header.Length && char.IsWhiteSpace(Header[pos]))
{
++pos;
}
if (pos >= Header.Length)
{
return EOF;
}
char c = Header[pos];
if (c == '(')
{
Token comment = ReadComment();
if (SkipComments)
{
return ReadToken();
}
else
{
return comment;
}
}
else if (c == '\"')
{
return ReadQuotedString();
}
else if (c < 32 || c >= 127 || Delimiters.Contains(new string(c, 1)))
{
pos++;
return new Token((int)c, new string(c, 1));
}
else
{
return ReadAtomicToken();
}
}
private Token ReadAtomicToken()
{
int start = pos;
while (++pos < Header.Length)
{
char c = Header[pos];
if (Delimiters.Contains(new string(c, 1)) || c < 32 || c >= 127)
{
break;
}
}
return new Token(Token.Atomic, Header.Substring(start, pos - start));
}
private Token ReadQuotedString()
{
int start = pos + 1;
bool requireEscape = false;
while (++pos < Header.Length)
{
char c = Header[pos];
if (c == '"')
{
string value;
if (requireEscape)
{
value = GetEscapedValue(start, pos - start);
}
else
{
value = Header.Substring(start, pos - start);
}
return new Token(Token.Comment, value);
}
else if (c == '\\')
{
pos++;
requireEscape = true;
}
else if (c == '\r')
{
requireEscape = true;
}
}
throw new ParseException("Missing '\"'");
}
private Token ReadComment()
{
int start = pos + 1;
int nesting = 1;
bool requireEscape = false;
while (++pos < Header.Length)
{
char c = Header[pos];
if (c == ')')
{
nesting--;
if (nesting == 0)
{
break;
}
}
else if (c == '(')
{
nesting++;
}
else if (c == '\\')
{
pos++;
requireEscape = true;
}
else if (c == '\r')
{
requireEscape = true;
}
}
if (nesting != 0)
{
throw new ParseException("Unbalanced comments");
}
string value;
if (requireEscape)
{
value = GetEscapedValue(start, pos);
}
else
{
value = Header.Substring(start, pos - start);