aboutsummaryrefslogtreecommitdiff
path: root/SocketHttpListener/Net/HttpListenerResponse.Managed.cs
blob: f595fce7ccad8ff9fa7828716daeb7c187b1a972 (plain)
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
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;

namespace SocketHttpListener.Net
{
    public sealed partial class HttpListenerResponse : IDisposable
    {
        private long _contentLength;
        private Version _version = HttpVersion.Version11;
        private int _statusCode = 200;
        internal object _headersLock = new object();
        private bool _forceCloseChunked;

        internal HttpListenerResponse(HttpListenerContext context)
        {
            _httpContext = context;
        }

        internal bool ForceCloseChunked => _forceCloseChunked;

        private void EnsureResponseStream()
        {
            if (_responseStream == null)
            {
                _responseStream = _httpContext.Connection.GetResponseStream();
            }
        }

        public Version ProtocolVersion
        {
            get => _version;
            set
            {
                CheckDisposed();
                if (value == null)
                {
                    throw new ArgumentNullException(nameof(value));
                }
                if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
                {
                    throw new ArgumentException("Wrong version");
                }

                _version = new Version(value.Major, value.Minor); // match Windows behavior, trimming to just Major.Minor
            }
        }

        public int StatusCode
        {
            get => _statusCode;
            set
            {
                CheckDisposed();

                if (value < 100 || value > 999)
                    throw new ProtocolViolationException("Invalid status");

                _statusCode = value;
            }
        }

        private void Dispose()
        {
            Close(true);
        }

        public void Close()
        {
            if (Disposed)
                return;

            Close(false);
        }

        public void Abort()
        {
            if (Disposed)
                return;

            Close(true);
        }

        private void Close(bool force)
        {
            Disposed = true;
            _httpContext.Connection.Close(force);
        }

        public void Close(byte[] responseEntity, bool willBlock)
        {
            CheckDisposed();

            if (responseEntity == null)
            {
                throw new ArgumentNullException(nameof(responseEntity));
            }

            if (!SentHeaders && _boundaryType != BoundaryType.Chunked)
            {
                ContentLength64 = responseEntity.Length;
            }

            if (willBlock)
            {
                try
                {
                    OutputStream.Write(responseEntity, 0, responseEntity.Length);
                }
                finally
                {
                    Close(false);
                }
            }
            else
            {
                OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar =>
                {
                    var thisRef = (HttpListenerResponse)iar.AsyncState;
                    try
                    {
                        try
                        {
                            thisRef.OutputStream.EndWrite(iar);
                        }
                        finally
                        {
                            thisRef.Close(false);
                        }
                    }
                    catch (Exception)
                    {
                        // In case response was disposed during this time
                    }
                }, this);
            }
        }

        public void CopyFrom(HttpListenerResponse templateResponse)
        {
            _webHeaders.Clear();
            //_webHeaders.Add(templateResponse._webHeaders);
            _contentLength = templateResponse._contentLength;
            _statusCode = templateResponse._statusCode;
            _statusDescription = templateResponse._statusDescription;
            _keepAlive = templateResponse._keepAlive;
            _version = templateResponse._version;
        }

        internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandshake = false)
        {
            if (!isWebSocketHandshake)
            {
                if (_webHeaders["Server"] == null)
                {
                    _webHeaders.Set("Server", "Microsoft-NetCore/2.0");
                }

                if (_webHeaders["Date"] == null)
                {
                    _webHeaders.Set("Date", DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
                }

                if (_boundaryType == BoundaryType.None)
                {
                    if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
                    {
                        _keepAlive = false;
                    }
                    else
                    {
                        _boundaryType = BoundaryType.Chunked;
                    }

                    if (CanSendResponseBody(_httpContext.Response.StatusCode))
                    {
                        _contentLength = -1;
                    }
                    else
                    {
                        _boundaryType = BoundaryType.ContentLength;
                        _contentLength = 0;
                    }
                }

                if (_boundaryType != BoundaryType.Chunked)
                {
                    if (_boundaryType != BoundaryType.ContentLength && closing)
                    {
                        _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0;
                    }

                    if (_boundaryType == BoundaryType.ContentLength)
                    {
                        _webHeaders.Set("Content-Length", _contentLength.ToString("D", CultureInfo.InvariantCulture));
                    }
                }

                /* Apache forces closing the connection for these status codes:
                 * HttpStatusCode.BadRequest            400
                 * HttpStatusCode.RequestTimeout        408
                 * HttpStatusCode.LengthRequired        411
                 * HttpStatusCode.RequestEntityTooLarge 413
                 * HttpStatusCode.RequestUriTooLong     414
                 * HttpStatusCode.InternalServerError   500
                 * HttpStatusCode.ServiceUnavailable    503
                 */
                bool conn_close = (_statusCode == (int)HttpStatusCode.BadRequest || _statusCode == (int)HttpStatusCode.RequestTimeout
                        || _statusCode == (int)HttpStatusCode.LengthRequired || _statusCode == (int)HttpStatusCode.RequestEntityTooLarge
                        || _statusCode == (int)HttpStatusCode.RequestUriTooLong || _statusCode == (int)HttpStatusCode.InternalServerError
                        || _statusCode == (int)HttpStatusCode.ServiceUnavailable);

                if (!conn_close)
                {
                    conn_close = !_httpContext.Request.KeepAlive;
                }

                // They sent both KeepAlive: true and Connection: close
                if (!_keepAlive || conn_close)
                {
                    _webHeaders.Set("Connection", "Close");
                    conn_close = true;
                }

                if (SendChunked)
                {
                    _webHeaders.Set("Transfer-Encoding", "Chunked");
                }

                int reuses = _httpContext.Connection.Reuses;
                if (reuses >= 100)
                {
                    _forceCloseChunked = true;
                    if (!conn_close)
                    {
                        _webHeaders.Set("Connection", "Close");
                        conn_close = true;
                    }
                }

                if (HttpListenerRequest.ProtocolVersion <= HttpVersion.Version10)
                {
                    if (_keepAlive)
                    {
                        Headers["Keep-Alive"] = "true";
                    }

                    if (!conn_close)
                    {
                        _webHeaders.Set("Connection", "Keep-Alive");
                    }
                }

                ComputeCookies();
            }

            var encoding = Encoding.UTF8;
            var writer = new StreamWriter(ms, encoding, 256);
            writer.Write("HTTP/1.1 {0} ", _statusCode); // "1.1" matches Windows implementation, which ignores the response version
            writer.Flush();
            byte[] statusDescriptionBytes = WebHeaderEncoding.GetBytes(StatusDescription);
            ms.Write(statusDescriptionBytes, 0, statusDescriptionBytes.Length);
            writer.Write("\r\n");

            writer.Write(FormatHeaders(_webHeaders));
            writer.Flush();
            int preamble = encoding.GetPreamble().Length;
            EnsureResponseStream();

            /* Assumes that the ms was at position 0 */
            ms.Position = preamble;
            SentHeaders = !isWebSocketHandshake;
        }

        private static bool HeaderCanHaveEmptyValue(string name) =>
            !string.Equals(name, "Location", StringComparison.OrdinalIgnoreCase);

        private static string FormatHeaders(WebHeaderCollection headers)
        {
            var sb = new StringBuilder();

            for (int i = 0; i < headers.Count; i++)
            {
                string key = headers.GetKey(i);
                string[] values = headers.GetValues(i);

                int startingLength = sb.Length;

                sb.Append(key).Append(": ");
                bool anyValues = false;
                for (int j = 0; j < values.Length; j++)
                {
                    string value = values[j];
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        if (anyValues)
                        {
                            sb.Append(", ");
                        }
                        sb.Append(value);
                        anyValues = true;
                    }
                }

                if (anyValues || HeaderCanHaveEmptyValue(key))
                {
                    // Complete the header
                    sb.Append("\r\n");
                }
                else
                {
                    // Empty header; remove it.
                    sb.Length = startingLength;
                }
            }

            return sb.Append("\r\n").ToString();
        }

        private bool Disposed { get; set; }
        internal bool SentHeaders { get; set; }

        public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
        {
            return ((HttpResponseStream)OutputStream).TransmitFile(path, offset, count, fileShareMode, cancellationToken);
        }
    }
}