/
ContentType.cs
288 lines (248 loc) · 9.71 KB
/
ContentType.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Net.Mail;
using System.Text;
namespace System.Net.Mime
{
// Typed Content-Type header
//
// We parse the type during construction and set.
// null and string.empty will throw for construction,set and mediatype/subtype
// constructors set isPersisted to false. isPersisted needs to be tracked separately
// than isChanged because isChanged only determines if the cached value should be used.
// isPersisted tracks if the object has been persisted. However, obviously if isChanged is true
// the object isn't persisted.
// If any subcomponents are changed, isChanged is set to true and isPersisted is false
// ToString caches the value until a isChanged is true, then it recomputes the full value.
public class ContentType
{
private readonly TrackingStringDictionary _parameters = new TrackingStringDictionary();
private string _mediaType;
private string _subType;
private bool _isChanged;
private string _type;
private bool _isPersisted;
/// <summary>
/// Default content type - can be used if the Content-Type header
/// is not defined in the message headers.
/// </summary>
internal const string Default = "application/octet-stream";
public ContentType() : this(Default)
{
}
/// <summary>
/// ctor.
/// </summary>
/// <param name="contentType">Unparsed value of the Content-Type header.</param>
public ContentType(string contentType)
{
ArgumentException.ThrowIfNullOrEmpty(contentType);
_isChanged = true;
_type = contentType;
ParseValue();
}
public string? Boundary
{
get { return Parameters["boundary"]; }
set
{
if (string.IsNullOrEmpty(value))
{
Parameters.Remove("boundary");
}
else
{
Parameters["boundary"] = value;
}
}
}
public string? CharSet
{
get { return Parameters["charset"]; }
set
{
if (string.IsNullOrEmpty(value))
{
Parameters.Remove("charset");
}
else
{
Parameters["charset"] = value;
}
}
}
/// <summary>
/// Gets the media type.
/// </summary>
public string MediaType
{
get { return _mediaType + "/" + _subType; }
set
{
ArgumentException.ThrowIfNullOrEmpty(value);
int offset = 0;
_mediaType = MailBnfHelper.ReadToken(value, ref offset);
if (_mediaType.Length == 0 || offset >= value.Length || value[offset++] != '/')
throw new FormatException(SR.MediaTypeInvalid);
_subType = MailBnfHelper.ReadToken(value, ref offset);
if (_subType.Length == 0 || offset < value.Length)
{
throw new FormatException(SR.MediaTypeInvalid);
}
_isChanged = true;
_isPersisted = false;
}
}
[AllowNull]
public string Name
{
get
{
string? value = Parameters["name"];
Encoding? nameEncoding = MimeBasePart.DecodeEncoding(value);
if (nameEncoding != null)
{
value = MimeBasePart.DecodeHeaderValue(value);
}
return value!;
}
set
{
if (value == null || value == string.Empty)
{
Parameters.Remove("name");
}
else
{
Parameters["name"] = value;
}
}
}
public StringDictionary Parameters => _parameters;
internal void Set(string contentType, HeaderCollection headers)
{
_type = contentType;
ParseValue();
headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, ToString());
_isPersisted = true;
}
internal void PersistIfNeeded(HeaderCollection headers, bool forcePersist)
{
if (IsChanged || !_isPersisted || forcePersist)
{
headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, ToString());
_isPersisted = true;
}
}
internal bool IsChanged => _isChanged || _parameters != null && _parameters.IsChanged;
public override string ToString()
{
if (_type == null || IsChanged)
{
_type = Encode(false); // Legacy wire-safe format
_isChanged = false;
_parameters.IsChanged = false;
_isPersisted = false;
}
return _type;
}
internal string Encode(bool allowUnicode)
{
var builder = new StringBuilder();
builder.Append(_mediaType); // Must not have unicode, already validated
builder.Append('/');
builder.Append(_subType); // Must not have unicode, already validated
// Validate and encode unicode where required
foreach (string key in Parameters.Keys)
{
builder.Append("; ");
EncodeToBuffer(key, builder, allowUnicode);
builder.Append('=');
EncodeToBuffer(_parameters[key]!, builder, allowUnicode);
}
return builder.ToString();
}
private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode)
{
Encoding? encoding = MimeBasePart.DecodeEncoding(value);
if (encoding != null) // Manually encoded elsewhere, pass through
{
builder.Append('\"').Append(value).Append('"');
}
else if ((allowUnicode && !MailBnfHelper.HasCROrLF(value)) // Unicode without CL or LF's
|| MimeBasePart.IsAscii(value, false)) // Ascii
{
MailBnfHelper.GetTokenOrQuotedString(value, builder, allowUnicode);
}
else
{
// MIME Encoding required
encoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
builder.Append('"').Append(MimeBasePart.EncodeHeaderValue(value, encoding, MimeBasePart.ShouldUseBase64Encoding(encoding))).Append('"');
}
}
public override bool Equals([NotNullWhen(true)] object? rparam) =>
rparam == null ? false : string.Equals(ToString(), rparam.ToString(), StringComparison.OrdinalIgnoreCase);
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(ToString());
// Helper methods.
[MemberNotNull(nameof(_mediaType))]
[MemberNotNull(nameof(_subType))]
private void ParseValue()
{
try
{
int offset = 0;
_mediaType = MailBnfHelper.ReadToken(_type, ref offset);
if (string.IsNullOrEmpty(_mediaType) || offset >= _type.Length || _type[offset++] != '/')
{
throw new FormatException(SR.ContentTypeInvalid);
}
_subType = MailBnfHelper.ReadToken(_type, ref offset);
if (string.IsNullOrEmpty(_subType))
{
throw new FormatException(SR.ContentTypeInvalid);
}
while (MailBnfHelper.SkipCFWS(_type, ref offset))
{
if (_type[offset++] != ';')
{
throw new FormatException(SR.ContentTypeInvalid);
}
if (!MailBnfHelper.SkipCFWS(_type, ref offset))
{
break;
}
string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset);
if (string.IsNullOrEmpty(paramAttribute))
{
throw new FormatException(SR.ContentTypeInvalid);
}
string? paramValue;
if (offset >= _type.Length || _type[offset++] != '=')
{
throw new FormatException(SR.ContentTypeInvalid);
}
if (!MailBnfHelper.SkipCFWS(_type, ref offset))
{
throw new FormatException(SR.ContentTypeInvalid);
}
paramValue = _type[offset] == '"' ?
MailBnfHelper.ReadQuotedString(_type, ref offset, null) :
MailBnfHelper.ReadToken(_type, ref offset);
if (paramValue == null)
{
throw new FormatException(SR.ContentTypeInvalid);
}
_parameters.Add(paramAttribute, paramValue);
}
_parameters.IsChanged = false;
}
catch (FormatException fe) when (fe.Message != SR.ContentTypeInvalid)
{
throw new FormatException(SR.ContentTypeInvalid);
}
}
}
}