2009-08-24 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Channels / PeerDuplexChannel.cs
1 //
2 // PeerDuplexChannel.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2009 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.IO;
32 using System.Net;
33 using System.Net.Security;
34 using System.Net.Sockets;
35 using System.ServiceModel;
36 using System.ServiceModel.Description;
37 using System.ServiceModel.PeerResolvers;
38 using System.ServiceModel.Security;
39 using System.Threading;
40 using System.Xml;
41
42 namespace System.ServiceModel.Channels
43 {
44
45         // PeerDuplexChannel can be created either from PeerChannelFactory
46         // (as IOutputChannel) or PeerChannelListener (as IInputChannel).
47         //
48         // PeerNode has to be created before Open() (at least at client side).
49         // On open, it tries to resolve the nodes in the mesh (and do something
50         // - but what?). Then registers itself to the mesh and refreshes it.
51
52         internal class PeerDuplexChannel : DuplexChannelBase
53         {
54                 enum RemotePeerStatus
55                 {
56                         None,
57                         Connected,
58                         Error,
59                 }
60
61                 class RemotePeerConnection
62                 {
63                         public RemotePeerConnection (PeerNodeAddress address)
64                         {
65                                 Address = address;
66                         }
67
68                         public PeerNodeAddress Address { get; private set; }
69                         public RemotePeerStatus Status { get; set; }
70                         public LocalPeerReceiver Instance { get; set; }
71                         public IPeerConnectorClient Channel { get; set; }
72                 }
73
74                 class LocalPeerReceiver : IPeerConnectorContract
75                 {
76                         List<PeerNodeAddress> connections = new List<PeerNodeAddress> ();
77                         AutoResetEvent connect_handle = new AutoResetEvent (false);
78
79                         public LocalPeerReceiver (PeerDuplexChannel owner)
80                         {
81                                 this.owner = owner;
82                         }
83
84                         PeerDuplexChannel owner;
85
86                         public void Connect (ConnectInfo connect)
87                         {
88                                 if (connect == null)
89                                         throw new ArgumentNullException ("connect");
90                                 var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
91
92                                 connections.Add (connect.Address);
93                                 // FIXME: check and reject if inappropriate. For example, maximum connection exceeded.
94                                 using (var octx = new OperationContextScope ((IContextChannel) ch)) {
95                                         OperationContext.Current.OutgoingMessageHeaders.To = new Uri (Constants.WsaAnonymousUri);
96                                         ch.Welcome (new WelcomeInfo () { NodeId = connect.NodeId });
97                                 }
98                         }
99
100                         internal void WaitForConnectResponse (TimeSpan timeout)
101                         {
102 Console.WriteLine ("##### Waiting for Welcome or Reject ...");
103                                 if (!connect_handle.WaitOne (timeout))
104                                         throw new TimeoutException ();
105                         }
106
107                         public void Disconnect (DisconnectInfo disconnect)
108                         {
109                                 if (disconnect == null)
110                                         throw new ArgumentNullException ("disconnect");
111                                 // Console.WriteLine ("DisconnectInfo.Reason: " + disconnect.Reason);
112                                 // FIXME: handle disconnection in practice. So far I see nothing to do.
113                         }
114
115                         public void Welcome (WelcomeInfo welcome)
116                         {
117 Console.WriteLine ("##### Welcome message received");
118                                 connect_handle.Set ();
119                         }
120
121                         public void Refuse (RefuseInfo refuse)
122                         {
123                                 // FIXME: it should not probably actually throw an error.
124                                 connect_handle.Set ();
125                                 throw new InvalidOperationException ("Peer connection was refused");
126                         }
127
128                         public void LinkUtility (LinkUtilityInfo linkUtility)
129                         {
130                                 throw new NotImplementedException ();
131                         }
132
133                         public void Ping ()
134                         {
135                                 throw new NotImplementedException ();
136                         }
137
138                         public void SendMessage (Message msg)
139                         {
140 Console.WriteLine ("##### non-connector message received: " + msg.Headers.Action);
141                                 owner.EnqueueMessage (msg);
142                         }
143                 }
144
145                 interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
146                 {
147                 }
148
149                 IChannelFactory<IDuplexSessionChannel> client_factory;
150                 ChannelFactory<IPeerConnectorClient> channel_factory;
151                 PeerTransportBindingElement binding;
152                 PeerResolver resolver;
153                 PeerNode node;
154                 ServiceHost listener_host;
155                 TcpChannelInfo info;
156                 List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
157                 PeerNodeAddress local_node_address;
158
159                 public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
160                         : base ((ChannelFactoryBase) factory, address, via)
161                 {
162                         binding = factory.Source;
163                         this.resolver = factory.Resolver;
164                         info = new TcpChannelInfo (binding, factory.MessageEncoder, null); // FIXME: fill properties correctly.
165
166                         // It could be opened even with empty list of PeerNodeAddresses.
167                         // So, do not create PeerNode per PeerNodeAddress, but do it with PeerNodeAddress[].
168                         node = new PeerNodeImpl (RemoteAddress.Uri.Host, factory.Source.ListenIPAddress, factory.Source.Port);
169                 }
170
171                 public PeerDuplexChannel (IPeerChannelManager listener)
172                         : base ((ChannelListenerBase) listener)
173                 {
174                         binding = listener.Source;
175                         this.resolver = listener.Resolver;
176                         info = new TcpChannelInfo (binding, listener.MessageEncoder, null); // FIXME: fill properties correctly.
177
178                         node = new PeerNodeImpl (((ChannelListenerBase) listener).Uri.Host, listener.Source.ListenIPAddress, listener.Source.Port);
179                 }
180
181                 public override T GetProperty<T> ()
182                 {
183                         if (typeof (T).IsInstanceOfType (node))
184                                 return (T) (object) node;
185                         return base.GetProperty<T> ();
186                 }
187
188                 // DuplexChannelBase
189
190                 IPeerConnectorClient CreateInnerClient (RemotePeerConnection conn)
191                 {
192                         conn.Instance = new LocalPeerReceiver (this);
193
194                         // FIXME: pass more setup parameters
195                         if (channel_factory == null) {
196                                 var binding = new NetTcpBinding ();
197                                 binding.Security.Mode = SecurityMode.None;
198                                 channel_factory = new DuplexChannelFactory<IPeerConnectorClient> (conn.Instance, binding);
199                         }
200
201                         return channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);
202                 }
203
204                 public override void Send (Message message, TimeSpan timeout)
205                 {
206                         ThrowIfDisposedOrNotOpen ();
207
208                         DateTime start = DateTime.Now;
209
210                         // FIXME: give max buffer size
211                         var mb = message.CreateBufferedCopy (0x10000);
212
213                         foreach (var pc in peers) {
214                                 message = mb.CreateMessage ();
215
216                                 if (pc.Status == RemotePeerStatus.None) {
217                                         pc.Status = RemotePeerStatus.Error; // prepare for cases that it resulted in an error in the middle.
218                                         var inner = CreateInnerClient (pc);
219                                         pc.Channel = inner;
220                                         inner.Open (timeout - (DateTime.Now - start));
221                                         inner.OperationTimeout = timeout - (DateTime.Now - start);
222                                         inner.Connect (new ConnectInfo () { Address = local_node_address, NodeId = (uint) node.NodeId });
223                                         pc.Instance.WaitForConnectResponse (timeout - (DateTime.Now - start));
224                                         pc.Status = RemotePeerStatus.Connected;
225                                 }
226
227                                 pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
228
229                                 if (message.Headers.MessageId == null)
230                                         message.Headers.MessageId = new UniqueId ();
231                                 message.Headers.Add (MessageHeader.CreateHeader ("PeerTo", Constants.NetPeer, RemoteAddress.Uri));
232                                 message.Headers.Add (MessageHeader.CreateHeader ("PeerVia", Constants.NetPeer, RemoteAddress.Uri));
233                                 pc.Channel.SendMessage (message);
234                         }
235                 }
236
237                 internal void EnqueueMessage (Message message)
238                 {
239                         queue.Enqueue (message);
240                         receive_handle.Set ();
241                 }
242
243                 Queue<Message> queue = new Queue<Message> ();
244                 AutoResetEvent receive_handle = new AutoResetEvent (false);
245
246                 public override Message Receive (TimeSpan timeout)
247                 {
248                         ThrowIfDisposedOrNotOpen ();
249                         DateTime start = DateTime.Now;
250
251                         if (queue.Count > 0)
252                                 return queue.Dequeue ();
253                         receive_handle.WaitOne ();
254                         return queue.Dequeue ();
255                 }
256
257                 public override bool WaitForMessage (TimeSpan timeout)
258                 {
259                         ThrowIfDisposedOrNotOpen ();
260
261                         throw new NotImplementedException ();
262                 }
263                 
264                 // CommunicationObject
265                 
266                 protected override void OnAbort ()
267                 {
268                         if (client_factory != null) {
269                                 client_factory.Abort ();
270                                 client_factory = null;
271                         }
272                         OnClose (TimeSpan.Zero);
273                 }
274
275                 protected override void OnClose (TimeSpan timeout)
276                 {
277                         DateTime start = DateTime.Now;
278                         if (client_factory != null)
279                                 client_factory.Close (timeout - (DateTime.Now - start));
280                         peers.Clear ();
281                         resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
282                         node.SetOffline ();
283                         if (listener_host != null)
284                                 listener_host.Close (timeout - (DateTime.Now - start));
285                         node.RegisteredId = null;
286                 }
287
288
289                 protected override void OnOpen (TimeSpan timeout)
290                 {
291                         DateTime start = DateTime.Now;
292
293                         // FIXME: supply maxAddresses
294                         foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
295                                 peers.Add (new RemotePeerConnection (a));
296
297                         // FIXME: pass more configuration
298                         var binding = new NetTcpBinding ();
299                         binding.Security.Mode = SecurityMode.None;
300
301                         int port = 0;
302                         var rnd = new Random ();
303                         for (int i = 0; i < 1000; i++) {
304                                 if (DateTime.Now - start > timeout)
305                                         throw new TimeoutException ();
306                                 try {
307                                         port = rnd.Next (50000, 51000);
308                                         var t = new TcpListener (port);
309                                         t.Start ();
310                                         t.Stop ();
311                                         break;
312                                 } catch (SocketException) {
313                                         continue;
314                                 }
315                         }
316
317                         string name = Dns.GetHostName ();
318                         var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
319
320                         var peer_receiver = new LocalPeerReceiver (this);
321                         listener_host = new ServiceHost (peer_receiver);
322                         var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
323                         sba.InstanceContextMode = InstanceContextMode.Single;
324                         sba.IncludeExceptionDetailInFaults = true;
325
326                         var se = listener_host.AddServiceEndpoint (typeof (IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");
327                         se.ListenUri = uri;
328
329                         // FIXME: remove debugging code
330                         listener_host.UnknownMessageReceived += delegate (object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine ("%%%%% UNKOWN MESSAGE " + earg.Message); };
331
332                         listener_host.Open (timeout - (DateTime.Now - start));
333
334                         var nid = new Random ().Next (0, int.MaxValue);
335                         var ea = new EndpointAddress (uri);
336                         var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
337                         local_node_address = pna;
338                         node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
339                         node.NodeId = nid;
340
341                         // Add itself to the local list as well.
342                         // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
343                         peers.Add (new RemotePeerConnection (pna));
344
345                         node.SetOnline ();
346                 }
347         }
348 }