TcpServerChannel.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. using System.Runtime.Remoting.Channels;
  37. namespace System.Runtime.Remoting.Channels.Tcp
  38. {
  39. public class TcpServerChannel : IChannelReceiver, IChannel
  40. {
  41. int port = 0;
  42. string name = "tcp";
  43. string host = null;
  44. int priority = 1;
  45. bool supressChannelData = false;
  46. bool useIpAddress = true;
  47. IPAddress bindAddress = IPAddress.Any;
  48. Thread server_thread = null;
  49. TcpListener listener;
  50. TcpServerTransportSink sink;
  51. ChannelDataStore channel_data;
  52. RemotingThreadPool threadPool;
  53. #if TARGET_JVM
  54. private volatile bool stopped = false;
  55. #endif
  56. void Init (IServerChannelSinkProvider serverSinkProvider)
  57. {
  58. if (serverSinkProvider == null)
  59. {
  60. serverSinkProvider = new BinaryServerFormatterSinkProvider ();
  61. }
  62. if (host == null)
  63. {
  64. if (useIpAddress) {
  65. if (!bindAddress.Equals(IPAddress.Any)) host = bindAddress.ToString ();
  66. else {
  67. IPHostEntry he = Dns.Resolve (Dns.GetHostName());
  68. if (he.AddressList.Length == 0) throw new RemotingException ("IP address could not be determined for this host");
  69. host = he.AddressList [0].ToString ();
  70. }
  71. }
  72. else
  73. host = Dns.GetHostByName(Dns.GetHostName()).HostName;
  74. }
  75. // Gets channel data from the chain of channel providers
  76. channel_data = new ChannelDataStore (null);
  77. IServerChannelSinkProvider provider = serverSinkProvider;
  78. while (provider != null)
  79. {
  80. provider.GetChannelData(channel_data);
  81. provider = provider.Next;
  82. }
  83. // Creates the sink chain that will process all incoming messages
  84. IServerChannelSink next_sink = ChannelServices.CreateServerChannelSinkChain (serverSinkProvider, this);
  85. sink = new TcpServerTransportSink (next_sink);
  86. }
  87. public TcpServerChannel (int port)
  88. {
  89. this.port = port;
  90. Init (null);
  91. }
  92. public TcpServerChannel (IDictionary properties,
  93. IServerChannelSinkProvider serverSinkProvider)
  94. {
  95. foreach(DictionaryEntry property in properties)
  96. {
  97. switch((string)property.Key)
  98. {
  99. case "name":
  100. name = property.Value.ToString();
  101. break;
  102. case "port":
  103. port = Convert.ToInt32(property.Value);
  104. break;
  105. case "priority":
  106. priority = Convert.ToInt32(property.Value);
  107. break;
  108. case "bindTo":
  109. bindAddress = IPAddress.Parse((string)property.Value);
  110. break;
  111. case "rejectRemoteRequests":
  112. if(Convert.ToBoolean(properties["rejectRemoteRequests"]))
  113. bindAddress = IPAddress.Loopback;
  114. break;
  115. case "supressChannelData":
  116. supressChannelData = Convert.ToBoolean (property.Value);
  117. break;
  118. case "useIpAddress":
  119. useIpAddress = Convert.ToBoolean (property.Value);
  120. break;
  121. case "machineName":
  122. host = property.Value as string;
  123. break;
  124. }
  125. }
  126. Init (serverSinkProvider);
  127. }
  128. public TcpServerChannel (string name, int port,
  129. IServerChannelSinkProvider serverSinkProvider)
  130. {
  131. this.name = name;
  132. this.port = port;
  133. Init (serverSinkProvider);
  134. }
  135. public TcpServerChannel (string name, int port)
  136. {
  137. this.name = name;
  138. this.port = port;
  139. Init (null);
  140. }
  141. public object ChannelData
  142. {
  143. get {
  144. if (supressChannelData) return null;
  145. else return channel_data;
  146. }
  147. }
  148. public string ChannelName
  149. {
  150. get {
  151. return name;
  152. }
  153. }
  154. public int ChannelPriority
  155. {
  156. get {
  157. return priority;
  158. }
  159. }
  160. public string GetChannelUri ()
  161. {
  162. return "tcp://" + host + ":" + port;
  163. }
  164. public string[] GetUrlsForUri (string uri)
  165. {
  166. if (!uri.StartsWith ("/")) uri = "/" + uri;
  167. string [] chnl_uris = channel_data.ChannelUris;
  168. string [] result = new String [chnl_uris.Length];
  169. for (int i = 0; i < chnl_uris.Length; i++)
  170. result [i] = chnl_uris [i] + uri;
  171. return result;
  172. }
  173. public string Parse (string url, out string objectURI)
  174. {
  175. return TcpChannel.ParseChannelUrl (url, out objectURI);
  176. }
  177. void WaitForConnections ()
  178. {
  179. try
  180. {
  181. #if !TARGET_JVM
  182. while(true)
  183. #else
  184. while(!stopped)
  185. #endif
  186. {
  187. Socket socket = listener.AcceptSocket ();
  188. ClientConnection reader = new ClientConnection (this, socket, sink);
  189. try {
  190. if (!threadPool.RunThread (new ThreadStart (reader.ProcessMessages)))
  191. socket.Close ();
  192. } catch (Exception e)
  193. {
  194. #if DEBUG
  195. Console.WriteLine("Exception caught in TcpServerChannel.WaitForConnections during start process message: {0} {1}", e.GetType(), e.Message);
  196. #endif
  197. }
  198. }
  199. }
  200. catch (Exception e)
  201. {
  202. #if DEBUG
  203. Console.WriteLine("Exception caught in TcpServerChannel.WaitForConnections, stop channel's thread : {0} {1}", e.GetType(), e.Message);
  204. #endif
  205. }
  206. }
  207. public void StartListening (object data)
  208. {
  209. #if TARGET_JVM
  210. stopped = false;
  211. #endif
  212. listener = new TcpListener (bindAddress, port);
  213. if (server_thread == null)
  214. {
  215. threadPool = RemotingThreadPool.GetSharedPool ();
  216. listener.Start ();
  217. if (port == 0)
  218. port = ((IPEndPoint)listener.LocalEndpoint).Port;
  219. string[] uris = new String [1];
  220. uris = new String [1];
  221. uris [0] = GetChannelUri ();
  222. channel_data.ChannelUris = uris;
  223. server_thread = new Thread (new ThreadStart (WaitForConnections));
  224. server_thread.IsBackground = true;
  225. server_thread.Start ();
  226. }
  227. }
  228. public void StopListening (object data)
  229. {
  230. #if TARGET_JVM
  231. stopped = true;
  232. #endif
  233. if (server_thread == null) return;
  234. #if !TARGET_JVM
  235. server_thread.Abort ();
  236. #else
  237. server_thread.Interrupt ();
  238. #endif
  239. listener.Stop ();
  240. threadPool.Free ();
  241. server_thread.Join ();
  242. server_thread = null;
  243. }
  244. }
  245. class ClientConnection
  246. {
  247. static int _count;
  248. int _id;
  249. Socket _socket;
  250. TcpServerTransportSink _sink;
  251. Stream _stream;
  252. byte[] _buffer = new byte[TcpMessageIO.DefaultStreamBufferSize];
  253. public ClientConnection (TcpServerChannel serverChannel, Socket socket, TcpServerTransportSink sink)
  254. {
  255. _socket = socket;
  256. _sink = sink;
  257. _id = _count++;
  258. }
  259. public Stream Stream
  260. {
  261. get { return _stream; }
  262. }
  263. public byte[] Buffer
  264. {
  265. get { return _buffer; }
  266. }
  267. public void ProcessMessages()
  268. {
  269. byte[] buffer = new byte[256];
  270. NetworkStream ns = new NetworkStream (_socket);
  271. _stream = new BufferedStream (ns);
  272. try
  273. {
  274. bool end = false;
  275. while (!end)
  276. {
  277. MessageStatus type = TcpMessageIO.ReceiveMessageStatus (_stream, buffer);
  278. switch (type)
  279. {
  280. case MessageStatus.MethodMessage:
  281. _sink.InternalProcessMessage (this);
  282. break;
  283. case MessageStatus.Unknown:
  284. case MessageStatus.CancelSignal:
  285. end = true;
  286. break;
  287. }
  288. _stream.Flush ();
  289. }
  290. }
  291. catch (Exception ex)
  292. {
  293. #if DEBUG
  294. Console.WriteLine ("The exception was caught during TcpServerChannel.ProcessMessages: {0}, {1}", ex.GetType(), ex.Message);
  295. #endif
  296. }
  297. finally
  298. {
  299. try {
  300. _stream.Close();
  301. _socket.Close ();
  302. }
  303. catch { }
  304. }
  305. }
  306. public int Id
  307. {
  308. get { return _id; }
  309. }
  310. public IPAddress ClientAddress
  311. {
  312. get {
  313. IPEndPoint ep = _socket.RemoteEndPoint as IPEndPoint;
  314. if (ep != null) return ep.Address;
  315. else return null;
  316. }
  317. }
  318. }
  319. }