2010-07-05 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Channels.Http / HttpListenerManager.cs
1 //
2 // HttpListenerManager.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2010 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Linq;
32 using System.Net;
33 using System.Net.Security;
34 using System.ServiceModel;
35 using System.ServiceModel.Channels;
36 using System.ServiceModel.Description;
37 using System.ServiceModel.Dispatcher;
38 using System.ServiceModel.Security;
39 using System.Text;
40 using System.Threading;
41
42 namespace System.ServiceModel.Channels.Http
43 {
44         internal class HttpListenerManager
45         {
46                 public HttpListenerManager (Uri uri)
47                 {
48                         var l = new HttpListener ();
49
50                         string uriString = uri.ToString ();
51                         if (!uriString.EndsWith ("/", StringComparison.Ordinal))
52                                 uriString += "/"; // HttpListener requires this mess.
53
54                         l.Prefixes.Add (uriString);
55
56                         this.listener = l;
57                 }
58                 
59                 HttpListener listener;
60                 List<HttpChannelListenerEntry> entries = new List<HttpChannelListenerEntry> ();
61
62                 Thread loop;
63
64                 // FIXME: use timeout
65                 public void RegisterListener (ChannelDispatcher channel, TimeSpan timeout)
66                 {
67                         entries.Add (new HttpChannelListenerEntry (channel, new AutoResetEvent (false)));
68
69                         entries.Sort (HttpChannelListenerEntry.CompareEntries);
70
71                         if (entries.Count != 1)
72                                 return;
73
74                         // Start here. It is shared between channel listeners
75                         // that share the same listen Uri. So there is no other appropriate place.
76 #if true
77                         loop = new Thread (new ThreadStart (delegate {
78                                 listener.Start ();
79                                 try {
80                                         while (true)
81                                                 ProcessNewContext (listener.GetContext ());
82                                 } catch (ThreadAbortException) {
83                                         Thread.ResetAbort ();
84                                 }
85                                 listener.Stop ();
86                         }));
87                         loop.Start ();
88 #else
89                         listener.BeginGetContext (GetContextCompleted, null);
90 #endif
91                 }
92
93                 // FIXME: use timeout
94                 public void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
95                 {
96                         var entry = entries.First (e => e.ChannelDispatcher == channel);
97                         entries.Remove (entry);
98
99                         entry.WaitHandle.Set (); // make sure to finish pending requests.
100
101                         // stop the server if there is no more registered listener.
102                         if (entries.Count > 0)
103                                 return;
104
105 #if true
106                         loop.Abort ();
107 #else
108                         this.listener.Stop ();
109 #endif
110                 }
111                 
112                 void GetContextCompleted (IAsyncResult result)
113                 {
114                         var ctx = listener.EndGetContext (result);
115                         ProcessNewContext (ctx);
116                         // start another listening
117                         listener.BeginGetContext (GetContextCompleted, null);
118                 }
119
120                 void ProcessNewContext (HttpListenerContext ctx)
121                 {
122                         if (ctx == null)
123                                 return;
124
125                         var ctxi = new HttpStandaloneContextInfo (ctx);
126                         var ce = SelectChannel (ctxi);
127                         if (ce == null)
128                                 throw new InvalidOperationException ("HttpListenerContext does not match any of the registered channels");
129                         ce.ContextQueue.Enqueue (ctxi);
130                         ce.WaitHandle.Set ();
131                 }
132
133                 HttpChannelListenerEntry SelectChannel (HttpContextInfo ctx)
134                 {
135                         foreach (var e in entries)
136                                 if (e.FilterHttpContext (ctx))
137                                         return e;
138                         return null;
139                 }
140
141                 public bool TryDequeueRequest (ChannelDispatcher channel, TimeSpan timeout, out HttpContextInfo context)
142                 {
143                         DateTime start = DateTime.Now;
144
145                         context = null;
146                         var ce = entries.First (e => e.ChannelDispatcher == channel);
147                         lock (ce.RetrieverLock) {
148                                 var q = ce.ContextQueue;
149                                 if (q.Count == 0) {
150                                         bool ret = ce.WaitHandle.WaitOne (timeout);
151                                         return ret && TryDequeueRequest (channel, timeout - (DateTime.Now - start), out context); // recurse, am lazy :/
152                                 }
153                                 context = q.Dequeue ();
154                                 return true;
155                         }
156                 }
157         }
158 }
159