aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Net/HttpServer.cs
blob: 7bb81c1ca10ee24c2c9f4837c0fa7d4912800873 (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
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
using Funq;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Model.Logging;
using ServiceStack.Api.Swagger;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.Logging.NLogger;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Cors;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.WebHost.Endpoints.Support;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MediaBrowser.Common.Net
{
    /// <summary>
    /// Class HttpServer
    /// </summary>
    public class HttpServer : HttpListenerBase
    {
        /// <summary>
        /// The logger
        /// </summary>
        private static ILogger Logger = Logging.LogManager.GetLogger("HttpServer");

        /// <summary>
        /// Gets the URL prefix.
        /// </summary>
        /// <value>The URL prefix.</value>
        public string UrlPrefix { get; private set; }

        /// <summary>
        /// Gets or sets the kernel.
        /// </summary>
        /// <value>The kernel.</value>
        private IKernel Kernel { get; set; }

        /// <summary>
        /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
        /// </summary>
        /// <value>The HTTP listener.</value>
        private IDisposable HttpListener { get; set; }

        /// <summary>
        /// Occurs when [web socket connected].
        /// </summary>
        public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;

        /// <summary>
        /// Gets the default redirect path.
        /// </summary>
        /// <value>The default redirect path.</value>
        public string DefaultRedirectPath { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="HttpServer" /> class.
        /// </summary>
        /// <param name="urlPrefix">The URL.</param>
        /// <param name="serverName">Name of the product.</param>
        /// <param name="kernel">The kernel.</param>
        /// <param name="defaultRedirectpath">The default redirectpath.</param>
        /// <exception cref="System.ArgumentNullException">urlPrefix</exception>
        public HttpServer(string urlPrefix, string serverName, IKernel kernel, string defaultRedirectpath = null)
            : base()
        {
            if (string.IsNullOrEmpty(urlPrefix))
            {
                throw new ArgumentNullException("urlPrefix");
            }

            DefaultRedirectPath = defaultRedirectpath;

            EndpointHostConfig.Instance.ServiceStackHandlerFactoryPath = null;
            EndpointHostConfig.Instance.MetadataRedirectPath = "metadata";

            UrlPrefix = urlPrefix;
            Kernel = kernel;

            EndpointHost.ConfigureHost(this, serverName, CreateServiceManager());

            ContentTypeFilters.Register(ContentType.ProtoBuf, (reqCtx, res, stream) => Kernel.ProtobufSerializer.SerializeToStream(res, stream), (type, stream) => Kernel.ProtobufSerializer.DeserializeFromStream(stream, type));

            Init();
            Start(urlPrefix);
        }

        /// <summary>
        /// Shut down the Web Service
        /// </summary>
        public override void Stop()
        {
            if (HttpListener != null)
            {
                HttpListener.Dispose();
                HttpListener = null;
            }

            if (Listener != null)
            {
                Listener.Prefixes.Remove(UrlPrefix);
            }

            base.Stop();
        }

        /// <summary>
        /// Configures the specified container.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            if (!string.IsNullOrEmpty(DefaultRedirectPath))
            {
                SetConfig(new EndpointHostConfig
                {
                    DefaultRedirectPath = DefaultRedirectPath,

                    // Tell SS to bubble exceptions up to here
                    WriteErrorsToResponse = false,

                    DebugMode = true
                });
            }
            
            container.Register(Kernel);

            foreach (var service in Kernel.RestServices)
            {
                service.Configure(this);
            }

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new CorsFeature());

            Serialization.JsonSerializer.Configure();

            LogManager.LogFactory = new NLogFactory();
        }

        /// <summary>
        /// Starts the Web Service
        /// </summary>
        /// <param name="urlBase">A Uri that acts as the base that the server is listening on.
        /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
        /// Note: the trailing slash is required! For more info see the
        /// HttpListener.Prefixes property on MSDN.</param>
        public override void Start(string urlBase)
        {
            // *** Already running - just leave it in place
            if (IsStarted)
            {
                return;
            }

            if (Listener == null)
            {
                Listener = new HttpListener();
            }

            EndpointHost.Config.ServiceStackHandlerFactoryPath = HttpListenerRequestWrapper.GetHandlerPathIfAny(urlBase);

            Listener.Prefixes.Add(urlBase);

            IsStarted = true;
            Listener.Start();

            HttpListener = CreateObservableStream().Subscribe(ProcessHttpRequestAsync);
        }

        /// <summary>
        /// Creates the observable stream.
        /// </summary>
        /// <returns>IObservable{HttpListenerContext}.</returns>
        private IObservable<HttpListenerContext> CreateObservableStream()
        {
            return Observable.Create<HttpListenerContext>(obs =>
                                Observable.FromAsync(() => Listener.GetContextAsync())
                                          .Subscribe(obs))
                             .Repeat()
                             .Retry()
                             .Publish()
                             .RefCount();
        }

        /// <summary>
        /// Processes incoming http requests by routing them to the appropiate handler
        /// </summary>
        /// <param name="context">The CTX.</param>
        private async void ProcessHttpRequestAsync(HttpListenerContext context)
        {
            LogHttpRequest(context);

            if (context.Request.IsWebSocketRequest)
            {
                await ProcessWebSocketRequest(context).ConfigureAwait(false);
                return;
            }

            RaiseReceiveWebRequest(context);

            try
            {
                ProcessRequest(context);
            }
            catch (InvalidOperationException ex)
            {
                HandleException(context.Response, ex, 422);

                throw;
            }
            catch (ResourceNotFoundException ex)
            {
                HandleException(context.Response, ex, 404);

                throw;
            }
            catch (FileNotFoundException ex)
            {
                HandleException(context.Response, ex, 404);

                throw;
            }
            catch (DirectoryNotFoundException ex)
            {
                HandleException(context.Response, ex, 404);

                throw;
            }
            catch (UnauthorizedAccessException ex)
            {
                HandleException(context.Response, ex, 401);

                throw;
            }
            catch (ArgumentException ex)
            {
                HandleException(context.Response, ex, 400);

                throw;
            }
            catch (Exception ex)
            {
                HandleException(context.Response, ex, 500);

                throw;
            }
        }

        /// <summary>
        /// Processes the web socket request.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <returns>Task.</returns>
        private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
        {
            try
            {
                var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);

                if (WebSocketConnected != null)
                {
                    WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket), Endpoint = ctx.Request.RemoteEndPoint });
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorException("AcceptWebSocketAsync error", ex);

                ctx.Response.StatusCode = 500;
                ctx.Response.Close();
            }
        }

        /// <summary>
        /// Logs the HTTP request.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        private void LogHttpRequest(HttpListenerContext ctx)
        {
            var log = new StringBuilder();

            log.AppendLine("Url: " + ctx.Request.Url);
            log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));

            var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;

            if (Kernel.Configuration.EnableHttpLevelLogging)
            {
                Logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
            }
        }

        /// <summary>
        /// Appends the error message.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="statusCode">The status code.</param>
        private void HandleException(HttpListenerResponse response, Exception ex, int statusCode)
        {
            Logger.ErrorException("Error processing request", ex);

            response.StatusCode = statusCode;

            response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));

            response.Headers.Remove("Age");
            response.Headers.Remove("Expires");
            response.Headers.Remove("Cache-Control");
            response.Headers.Remove("Etag");
            response.Headers.Remove("Last-Modified");

            response.ContentType = "text/plain";

            if (!string.IsNullOrEmpty(ex.Message))
            {
                response.AddHeader("X-Application-Error-Code", ex.Message);
            }

            // This could fail, but try to add the stack trace as the body content
            try
            {
                var sb = new StringBuilder();
                sb.AppendLine("{");
                sb.AppendLine("\"ResponseStatus\":{");
                sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.GetType().Name.EncodeJson());
                sb.AppendFormat(" \"Message\":{0},\n", ex.Message.EncodeJson());
                sb.AppendFormat(" \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson());
                sb.AppendLine("}");
                sb.AppendLine("}");

                response.StatusCode = 500;
                response.ContentType = ContentType.Json;
                var sbBytes = sb.ToString().ToUtf8Bytes();
                response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
                response.Close();
            }
            catch (Exception errorEx)
            {
                Logger.ErrorException("Error processing failed request", errorEx);
            }
        }


        /// <summary>
        /// Overridable method that can be used to implement a custom hnandler
        /// </summary>
        /// <param name="context">The context.</param>
        /// <exception cref="System.NotImplementedException">Cannot execute handler:  + handler +  at PathInfo:  + httpReq.PathInfo</exception>
        protected override void ProcessRequest(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl)) return;

            var operationName = context.Request.GetOperationName();

            var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
            var httpRes = new HttpListenerResponseWrapper(context.Response);
            var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHttpHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
                }
                serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
                LogResponse(context);
                httpRes.Close();
                return;
            }

            throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
        }

        /// <summary>
        /// Logs the response.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        private void LogResponse(HttpListenerContext ctx)
        {
            var statusode = ctx.Response.StatusCode;

            var log = new StringBuilder();

            log.AppendLine(string.Format("Url: {0}", ctx.Request.Url));

            log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));

            var msg = "Http Response Sent (" + statusode + ") to " + ctx.Request.RemoteEndPoint;

            if (Kernel.Configuration.EnableHttpLevelLogging)
            {
                Logger.LogMultiline(msg, LogSeverity.Debug, log);
            }
        }

        /// <summary>
        /// Creates the service manager.
        /// </summary>
        /// <param name="assembliesWithServices">The assemblies with services.</param>
        /// <returns>ServiceManager.</returns>
        protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
        {
            var types = Kernel.RestServices.Select(r => r.GetType()).ToArray();

            return new ServiceManager(new Container(), new ServiceController(() => types));
        }
    }

    /// <summary>
    /// Class WebSocketConnectEventArgs
    /// </summary>
    public class WebSocketConnectEventArgs : EventArgs
    {
        /// <summary>
        /// Gets or sets the web socket.
        /// </summary>
        /// <value>The web socket.</value>
        public IWebSocket WebSocket { get; set; }
        /// <summary>
        /// Gets or sets the endpoint.
        /// </summary>
        /// <value>The endpoint.</value>
        public IPEndPoint Endpoint { get; set; }
    }
}