TcpServerChannel.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 serverSinkProvider)
  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 (serverSinkProvider);
  128. }
  129. public TcpServerChannel (string name, int port,
  130. IServerChannelSinkProvider serverSinkProvider)
  131. {
  132. this.name = name;
  133. this.port = port;
  134. Init (serverSinkProvider);
  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 uri)
  166. {
  167. if (!uri.StartsWith ("/")) uri = "/" + uri;
  168. string [] chnl_uris = channel_data.ChannelUris;
  169. string [] result = new String [chnl_uris.Length];
  170. for (int i = 0; i < chnl_uris.Length; i++)
  171. result [i] = chnl_uris [i] + uri;
  172. return result;
  173. }
  174. public string Parse (string url, out string objectURI)
  175. {
  176. return TcpChannel.ParseChannelUrl (url, out objectURI);
  177. }
  178. void WaitForConnections ()
  179. {
  180. try
  181. {
  182. #if !TARGET_JVM
  183. while(true)
  184. #else
  185. while(!stopped)
  186. #endif
  187. {
  188. Socket socket = listener.AcceptSocket ();
  189. ClientConnection reader = new ClientConnection (this, socket, sink);
  190. try {
  191. if (!threadPool.RunThread (new ThreadStart (reader.ProcessMessages)))
  192. socket.Close ();
  193. } catch (Exception e)
  194. {
  195. #if DEBUG
  196. Console.WriteLine("Exception caught in TcpServerChannel.WaitForConnections during start process message: {0} {1}", e.GetType(), e.Message);
  197. #endif
  198. }
  199. }
  200. }
  201. catch (Exception e)
  202. {
  203. #if DEBUG
  204. Console.WriteLine("Exception caught in TcpServerChannel.WaitForConnections, stop channel's thread : {0} {1}", e.GetType(), e.Message);
  205. #endif
  206. }
  207. }
  208. public void StartListening (object data)
  209. {
  210. #if TARGET_JVM
  211. stopped = false;
  212. #endif
  213. listener = new TcpListener (bindAddress, port);
  214. if (server_thread == null)
  215. {
  216. threadPool = RemotingThreadPool.GetSharedPool ();
  217. listener.Start ();
  218. if (port == 0)
  219. port = ((IPEndPoint)listener.LocalEndpoint).Port;
  220. string[] uris = new String [1];
  221. uris = new String [1];
  222. uris [0] = GetChannelUri ();
  223. channel_data.ChannelUris = uris;
  224. server_thread = new Thread (new ThreadStart (WaitForConnections));
  225. server_thread.IsBackground = true;
  226. server_thread.Start ();
  227. }
  228. }
  229. public void StopListening (object data)
  230. {
  231. #if TARGET_JVM
  232. stopped = true;
  233. #endif
  234. if (server_thread == null) return;
  235. #if !TARGET_JVM
  236. server_thread.Abort ();
  237. #else
  238. server_thread.Interrupt ();
  239. #endif
  240. listener.Stop ();
  241. threadPool.Free ();
  242. server_thread.Join ();
  243. server_thread = null;
  244. }
  245. }
  246. class ClientConnection
  247. {
  248. static int _count;
  249. int _id;
  250. Socket _socket;
  251. TcpServerTransportSink _sink;
  252. Stream _stream;
  253. byte[] _buffer = new byte[TcpMessageIO.DefaultStreamBufferSize];
  254. public ClientConnection (TcpServerChannel serverChannel, Socket socket, TcpServerTransportSink sink)
  255. {
  256. _socket = socket;
  257. _sink = sink;
  258. _id = _count++;
  259. }
  260. public Socket Socket {
  261. get { return _socket; }
  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, _stream);
  282. break;
  283. case MessageStatus.Unknown:
  284. case MessageStatus.CancelSignal:
  285. _stream.Flush ();
  286. end = true;
  287. break;
  288. }
  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. }