TcpServerChannel.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. StartListening (null);
  87. }
  88. public TcpServerChannel (int port)
  89. {
  90. this.port = port;
  91. Init (null);
  92. }
  93. public TcpServerChannel (IDictionary properties,
  94. IServerChannelSinkProvider sinkProvider)
  95. {
  96. foreach(DictionaryEntry property in properties)
  97. {
  98. switch((string)property.Key)
  99. {
  100. case "name":
  101. name = property.Value.ToString();
  102. break;
  103. case "port":
  104. port = Convert.ToInt32(property.Value);
  105. break;
  106. case "priority":
  107. priority = Convert.ToInt32(property.Value);
  108. break;
  109. case "bindTo":
  110. bindAddress = IPAddress.Parse((string)property.Value);
  111. break;
  112. case "rejectRemoteRequests":
  113. if(Convert.ToBoolean(properties["rejectRemoteRequests"]))
  114. bindAddress = IPAddress.Loopback;
  115. break;
  116. case "supressChannelData":
  117. supressChannelData = Convert.ToBoolean (property.Value);
  118. break;
  119. case "useIpAddress":
  120. useIpAddress = Convert.ToBoolean (property.Value);
  121. break;
  122. case "machineName":
  123. host = property.Value as string;
  124. break;
  125. }
  126. }
  127. Init (sinkProvider);
  128. }
  129. public TcpServerChannel (string name, int port,
  130. IServerChannelSinkProvider sinkProvider)
  131. {
  132. this.name = name;
  133. this.port = port;
  134. Init (sinkProvider);
  135. }
  136. public TcpServerChannel (string name, int port)
  137. {
  138. this.name = name;
  139. this.port = port;
  140. Init (null);
  141. }
  142. public object ChannelData
  143. {
  144. get {
  145. if (supressChannelData) return null;
  146. else return channel_data;
  147. }
  148. }
  149. public string ChannelName
  150. {
  151. get {
  152. return name;
  153. }
  154. }
  155. public int ChannelPriority
  156. {
  157. get {
  158. return priority;
  159. }
  160. }
  161. public string GetChannelUri ()
  162. {
  163. return "tcp://" + host + ":" + port;
  164. }
  165. public virtual string [] GetUrlsForUri (string objectUri)
  166. {
  167. if (!objectUri.StartsWith ("/"))
  168. objectUri = "/" + objectUri;
  169. string [] chnl_uris = channel_data.ChannelUris;
  170. string [] result = new String [chnl_uris.Length];
  171. for (int i = 0; i < chnl_uris.Length; i++)
  172. result [i] = chnl_uris [i] + objectUri;
  173. return result;
  174. }
  175. public string Parse (string url, out string objectURI)
  176. {
  177. return TcpChannel.ParseChannelUrl (url, out objectURI);
  178. }
  179. void WaitForConnections ()
  180. {
  181. try
  182. {
  183. #if !TARGET_JVM
  184. while(true)
  185. #else
  186. while(!stopped)
  187. #endif
  188. {
  189. Socket socket = listener.AcceptSocket ();
  190. ClientConnection reader = new ClientConnection (this, socket, sink);
  191. try {
  192. if (!threadPool.RunThread (new ThreadStart (reader.ProcessMessages)))
  193. socket.Close ();
  194. } catch (Exception e)
  195. {
  196. #if DEBUG
  197. Console.WriteLine("Exception caught in TcpServerChannel.WaitForConnections during start process message: {0} {1}", e.GetType(), e.Message);
  198. #endif
  199. }
  200. }
  201. }
  202. catch (Exception e)
  203. {
  204. #if DEBUG
  205. Console.WriteLine("Exception caught in TcpServerChannel.WaitForConnections, stop channel's thread : {0} {1}", e.GetType(), e.Message);
  206. #endif
  207. }
  208. }
  209. public void StartListening (object data)
  210. {
  211. #if TARGET_JVM
  212. stopped = false;
  213. #endif
  214. listener = new TcpListener (bindAddress, port);
  215. if (server_thread == null)
  216. {
  217. threadPool = RemotingThreadPool.GetSharedPool ();
  218. listener.Start ();
  219. if (port == 0)
  220. port = ((IPEndPoint)listener.LocalEndpoint).Port;
  221. string[] uris = new String [1];
  222. uris = new String [1];
  223. uris [0] = GetChannelUri ();
  224. channel_data.ChannelUris = uris;
  225. server_thread = new Thread (new ThreadStart (WaitForConnections));
  226. server_thread.IsBackground = true;
  227. server_thread.Start ();
  228. }
  229. }
  230. public void StopListening (object data)
  231. {
  232. #if TARGET_JVM
  233. stopped = true;
  234. #endif
  235. if (server_thread == null) return;
  236. #if !TARGET_JVM
  237. server_thread.Abort ();
  238. #else
  239. server_thread.Interrupt ();
  240. #endif
  241. listener.Stop ();
  242. threadPool.Free ();
  243. server_thread.Join ();
  244. server_thread = null;
  245. }
  246. }
  247. class ClientConnection
  248. {
  249. static int _count;
  250. int _id;
  251. Socket _socket;
  252. TcpServerTransportSink _sink;
  253. Stream _stream;
  254. byte[] _buffer = new byte[TcpMessageIO.DefaultStreamBufferSize];
  255. public ClientConnection (TcpServerChannel serverChannel, Socket socket, TcpServerTransportSink sink)
  256. {
  257. _socket = socket;
  258. _sink = sink;
  259. _id = _count++;
  260. }
  261. public Socket Socket {
  262. get { return _socket; }
  263. }
  264. public byte[] Buffer
  265. {
  266. get { return _buffer; }
  267. }
  268. public void ProcessMessages()
  269. {
  270. byte[] buffer = new byte[256];
  271. NetworkStream ns = new NetworkStream (_socket);
  272. _stream = new BufferedStream (ns);
  273. try
  274. {
  275. bool end = false;
  276. while (!end)
  277. {
  278. MessageStatus type = TcpMessageIO.ReceiveMessageStatus (_stream, buffer);
  279. switch (type)
  280. {
  281. case MessageStatus.MethodMessage:
  282. _sink.InternalProcessMessage (this, _stream);
  283. break;
  284. case MessageStatus.Unknown:
  285. case MessageStatus.CancelSignal:
  286. _stream.Flush ();
  287. end = true;
  288. break;
  289. }
  290. }
  291. }
  292. catch (Exception ex)
  293. {
  294. #if DEBUG
  295. Console.WriteLine ("The exception was caught during TcpServerChannel.ProcessMessages: {0}, {1}", ex.GetType(), ex.Message);
  296. #endif
  297. }
  298. finally
  299. {
  300. try {
  301. _stream.Close();
  302. _socket.Close ();
  303. }
  304. catch { }
  305. }
  306. }
  307. public int Id
  308. {
  309. get { return _id; }
  310. }
  311. public IPAddress ClientAddress
  312. {
  313. get {
  314. IPEndPoint ep = _socket.RemoteEndPoint as IPEndPoint;
  315. if (ep != null) return ep.Address;
  316. else return null;
  317. }
  318. }
  319. }
  320. }