TcpServerChannel.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // System.Runtime.Remoting.Channels.Tcp.TcpServerChannel.cs
  3. //
  4. // Author: Rodrigo Moya ([email protected])
  5. // Lluis Sanchez Gual ([email protected])
  6. //
  7. // 2002 (C) Copyright, Ximian, Inc.
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Collections;
  30. using System.Runtime.Remoting.Messaging;
  31. using System.Text.RegularExpressions;
  32. using System.Net.Sockets;
  33. using System.Net;
  34. using System.Threading;
  35. using System.IO;
  36. namespace System.Runtime.Remoting.Channels.Tcp
  37. {
  38. public class TcpServerChannel : IChannelReceiver, IChannel
  39. {
  40. int port = 0;
  41. string name = "tcp";
  42. string host = null;
  43. int priority = 1;
  44. bool supressChannelData = false;
  45. bool useIpAddress = false;
  46. IPAddress bindAddress = IPAddress.Any;
  47. Thread server_thread = null;
  48. TcpListener listener;
  49. TcpServerTransportSink sink;
  50. ChannelDataStore channel_data;
  51. int _maxConcurrentConnections = 100;
  52. ArrayList _activeConnections = new ArrayList();
  53. void Init (IServerChannelSinkProvider serverSinkProvider)
  54. {
  55. if (serverSinkProvider == null)
  56. {
  57. serverSinkProvider = new BinaryServerFormatterSinkProvider ();
  58. }
  59. if (host == null)
  60. {
  61. if (useIpAddress) {
  62. if (!bindAddress.Equals(IPAddress.Any)) host = bindAddress.ToString ();
  63. else {
  64. IPHostEntry he = Dns.Resolve (Dns.GetHostName());
  65. if (he.AddressList.Length == 0) throw new RemotingException ("IP address could not be determined for this host");
  66. host = he.AddressList [0].ToString ();
  67. }
  68. }
  69. else
  70. host = Dns.GetHostByName(Dns.GetHostName()).HostName;
  71. }
  72. // Gets channel data from the chain of channel providers
  73. channel_data = new ChannelDataStore (null);
  74. IServerChannelSinkProvider provider = serverSinkProvider;
  75. while (provider != null)
  76. {
  77. provider.GetChannelData(channel_data);
  78. provider = provider.Next;
  79. }
  80. // Creates the sink chain that will process all incoming messages
  81. IServerChannelSink next_sink = ChannelServices.CreateServerChannelSinkChain (serverSinkProvider, this);
  82. sink = new TcpServerTransportSink (next_sink);
  83. }
  84. public TcpServerChannel (int port)
  85. {
  86. this.port = port;
  87. Init (null);
  88. }
  89. public TcpServerChannel (IDictionary properties,
  90. IServerChannelSinkProvider serverSinkProvider)
  91. {
  92. foreach(DictionaryEntry property in properties)
  93. {
  94. switch((string)property.Key)
  95. {
  96. case "name":
  97. name = property.Value.ToString();
  98. break;
  99. case "port":
  100. port = Convert.ToInt32(property.Value);
  101. break;
  102. case "priority":
  103. priority = Convert.ToInt32(property.Value);
  104. break;
  105. case "bindTo":
  106. bindAddress = IPAddress.Parse((string)property.Value);
  107. break;
  108. case "rejectRemoteRequests":
  109. if(Convert.ToBoolean(properties["rejectRemoteRequests"]))
  110. bindAddress = IPAddress.Loopback;
  111. break;
  112. case "supressChannelData":
  113. supressChannelData = Convert.ToBoolean (property.Value);
  114. break;
  115. case "useIpAddress":
  116. useIpAddress = Convert.ToBoolean (property.Value);
  117. break;
  118. case "machineName":
  119. host = property.Value as string;
  120. break;
  121. }
  122. }
  123. Init (serverSinkProvider);
  124. }
  125. public TcpServerChannel (string name, int port,
  126. IServerChannelSinkProvider serverSinkProvider)
  127. {
  128. this.name = name;
  129. this.port = port;
  130. Init (serverSinkProvider);
  131. }
  132. public TcpServerChannel (string name, int port)
  133. {
  134. this.name = name;
  135. this.port = port;
  136. Init (null);
  137. }
  138. public object ChannelData
  139. {
  140. get {
  141. if (supressChannelData) return null;
  142. else return channel_data;
  143. }
  144. }
  145. public string ChannelName
  146. {
  147. get {
  148. return name;
  149. }
  150. }
  151. public int ChannelPriority
  152. {
  153. get {
  154. return priority;
  155. }
  156. }
  157. public string GetChannelUri ()
  158. {
  159. return "tcp://" + host + ":" + port;
  160. }
  161. public string[] GetUrlsForUri (string uri)
  162. {
  163. if (!uri.StartsWith ("/")) uri = "/" + uri;
  164. string [] chnl_uris = channel_data.ChannelUris;
  165. string [] result = new String [chnl_uris.Length];
  166. for (int i = 0; i < chnl_uris.Length; i++)
  167. result [i] = chnl_uris [i] + uri;
  168. return result;
  169. }
  170. public string Parse (string url, out string objectURI)
  171. {
  172. return TcpChannel.ParseChannelUrl (url, out objectURI);
  173. }
  174. void WaitForConnections ()
  175. {
  176. try
  177. {
  178. while (true)
  179. {
  180. TcpClient client = listener.AcceptTcpClient ();
  181. CreateListenerConnection (client);
  182. }
  183. }
  184. catch
  185. {}
  186. }
  187. internal void CreateListenerConnection (TcpClient client)
  188. {
  189. lock (_activeConnections)
  190. {
  191. if (_activeConnections.Count >= _maxConcurrentConnections)
  192. Monitor.Wait (_activeConnections);
  193. if (server_thread == null) return; // Server was stopped while waiting
  194. ClientConnection reader = new ClientConnection (this, client, sink);
  195. Thread thread = new Thread (new ThreadStart (reader.ProcessMessages));
  196. thread.Start();
  197. thread.IsBackground = true;
  198. _activeConnections.Add (thread);
  199. }
  200. }
  201. internal void ReleaseConnection (Thread thread)
  202. {
  203. lock (_activeConnections)
  204. {
  205. _activeConnections.Remove (thread);
  206. Monitor.Pulse (_activeConnections);
  207. }
  208. }
  209. public void StartListening (object data)
  210. {
  211. listener = new TcpListener (bindAddress, port);
  212. if (server_thread == null)
  213. {
  214. listener.Start ();
  215. if (port == 0)
  216. port = ((IPEndPoint)listener.LocalEndpoint).Port;
  217. string[] uris = new String [1];
  218. uris = new String [1];
  219. uris [0] = GetChannelUri ();
  220. channel_data.ChannelUris = uris;
  221. server_thread = new Thread (new ThreadStart (WaitForConnections));
  222. server_thread.IsBackground = true;
  223. server_thread.Start ();
  224. }
  225. }
  226. public void StopListening (object data)
  227. {
  228. if (server_thread == null) return;
  229. lock (_activeConnections)
  230. {
  231. server_thread.Abort ();
  232. server_thread = null;
  233. listener.Stop ();
  234. foreach (Thread thread in _activeConnections)
  235. thread.Abort();
  236. _activeConnections.Clear();
  237. Monitor.PulseAll (_activeConnections);
  238. }
  239. }
  240. }
  241. class ClientConnection
  242. {
  243. TcpClient _client;
  244. TcpServerTransportSink _sink;
  245. Stream _stream;
  246. TcpServerChannel _serverChannel;
  247. byte[] _buffer = new byte[TcpMessageIO.DefaultStreamBufferSize];
  248. public ClientConnection (TcpServerChannel serverChannel, TcpClient client, TcpServerTransportSink sink)
  249. {
  250. _serverChannel = serverChannel;
  251. _client = client;
  252. _sink = sink;
  253. }
  254. public Stream Stream
  255. {
  256. get { return _stream; }
  257. }
  258. public byte[] Buffer
  259. {
  260. get { return _buffer; }
  261. }
  262. public void ProcessMessages()
  263. {
  264. _stream = _client.GetStream();
  265. try
  266. {
  267. bool end = false;
  268. while (!end)
  269. {
  270. MessageStatus type = TcpMessageIO.ReceiveMessageStatus (_stream);
  271. switch (type)
  272. {
  273. case MessageStatus.MethodMessage:
  274. _sink.InternalProcessMessage (this);
  275. break;
  276. case MessageStatus.CancelSignal:
  277. end = true;
  278. break;
  279. }
  280. }
  281. }
  282. catch (Exception ex)
  283. {
  284. // Console.WriteLine (ex);
  285. }
  286. finally
  287. {
  288. _stream.Close();
  289. _serverChannel.ReleaseConnection (Thread.CurrentThread);
  290. }
  291. }
  292. public bool IsLocal
  293. {
  294. get
  295. {
  296. return true;
  297. }
  298. }
  299. }
  300. }