TelnetAppender.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. #region Apache License
  2. //
  3. // Licensed to the Apache Software Foundation (ASF) under one or more
  4. // contributor license agreements. See the NOTICE file distributed with
  5. // this work for additional information regarding copyright ownership.
  6. // The ASF licenses this file to you under the Apache License, Version 2.0
  7. // (the "License"); you may not use this file except in compliance with
  8. // the License. You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. //
  18. #endregion
  19. using System;
  20. using System.Collections;
  21. using System.Globalization;
  22. using System.Net;
  23. using System.Net.Sockets;
  24. using System.Text;
  25. using System.IO;
  26. using System.Threading;
  27. #if NETSTANDARD1_3
  28. using System.Threading.Tasks;
  29. #endif
  30. using log4net.Layout;
  31. using log4net.Core;
  32. using log4net.Util;
  33. namespace log4net.Appender
  34. {
  35. /// <summary>
  36. /// Appender that allows clients to connect via Telnet to receive log messages
  37. /// </summary>
  38. /// <remarks>
  39. /// <para>
  40. /// The TelnetAppender accepts socket connections and streams logging messages
  41. /// back to the client.
  42. /// The output is provided in a telnet-friendly way so that a log can be monitored
  43. /// over a TCP/IP socket.
  44. /// This allows simple remote monitoring of application logging.
  45. /// </para>
  46. /// <para>
  47. /// The default <see cref="Port"/> is 23 (the telnet port).
  48. /// </para>
  49. /// </remarks>
  50. /// <author>Keith Long</author>
  51. /// <author>Nicko Cadell</author>
  52. public class TelnetAppender : AppenderSkeleton
  53. {
  54. private SocketHandler m_handler;
  55. private int m_listeningPort = 23;
  56. #region Constructor
  57. /// <summary>
  58. /// Default constructor
  59. /// </summary>
  60. /// <remarks>
  61. /// <para>
  62. /// Default constructor
  63. /// </para>
  64. /// </remarks>
  65. public TelnetAppender()
  66. {
  67. }
  68. #endregion
  69. #region Private Static Fields
  70. /// <summary>
  71. /// The fully qualified type of the TelnetAppender class.
  72. /// </summary>
  73. /// <remarks>
  74. /// Used by the internal logger to record the Type of the
  75. /// log message.
  76. /// </remarks>
  77. private readonly static Type declaringType = typeof(TelnetAppender);
  78. #endregion Private Static Fields
  79. /// <summary>
  80. /// Gets or sets the TCP port number on which this <see cref="TelnetAppender"/> will listen for connections.
  81. /// </summary>
  82. /// <value>
  83. /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
  84. /// indicating the TCP port number on which this <see cref="TelnetAppender"/> will listen for connections.
  85. /// </value>
  86. /// <remarks>
  87. /// <para>
  88. /// The default value is 23 (the telnet port).
  89. /// </para>
  90. /// </remarks>
  91. /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" />
  92. /// or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
  93. public int Port
  94. {
  95. get
  96. {
  97. return m_listeningPort;
  98. }
  99. set
  100. {
  101. if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)
  102. {
  103. throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
  104. "The value specified for Port is less than " +
  105. IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
  106. " or greater than " +
  107. IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
  108. }
  109. else
  110. {
  111. m_listeningPort = value;
  112. }
  113. }
  114. }
  115. #region Override implementation of AppenderSkeleton
  116. /// <summary>
  117. /// Overrides the parent method to close the socket handler
  118. /// </summary>
  119. /// <remarks>
  120. /// <para>
  121. /// Closes all the outstanding connections.
  122. /// </para>
  123. /// </remarks>
  124. protected override void OnClose()
  125. {
  126. base.OnClose();
  127. if (m_handler != null)
  128. {
  129. m_handler.Dispose();
  130. m_handler = null;
  131. }
  132. }
  133. /// <summary>
  134. /// This appender requires a <see cref="Layout"/> to be set.
  135. /// </summary>
  136. /// <value><c>true</c></value>
  137. /// <remarks>
  138. /// <para>
  139. /// This appender requires a <see cref="Layout"/> to be set.
  140. /// </para>
  141. /// </remarks>
  142. protected override bool RequiresLayout
  143. {
  144. get { return true; }
  145. }
  146. /// <summary>
  147. /// Initialize the appender based on the options set.
  148. /// </summary>
  149. /// <remarks>
  150. /// <para>
  151. /// This is part of the <see cref="IOptionHandler"/> delayed object
  152. /// activation scheme. The <see cref="ActivateOptions"/> method must
  153. /// be called on this object after the configuration properties have
  154. /// been set. Until <see cref="ActivateOptions"/> is called this
  155. /// object is in an undefined state and must not be used.
  156. /// </para>
  157. /// <para>
  158. /// If any of the configuration properties are modified then
  159. /// <see cref="ActivateOptions"/> must be called again.
  160. /// </para>
  161. /// <para>
  162. /// Create the socket handler and wait for connections
  163. /// </para>
  164. /// </remarks>
  165. public override void ActivateOptions()
  166. {
  167. base.ActivateOptions();
  168. try
  169. {
  170. LogLog.Debug(declaringType, "Creating SocketHandler to listen on port ["+m_listeningPort+"]");
  171. m_handler = new SocketHandler(m_listeningPort);
  172. }
  173. catch(Exception ex)
  174. {
  175. LogLog.Error(declaringType, "Failed to create SocketHandler", ex);
  176. throw;
  177. }
  178. }
  179. /// <summary>
  180. /// Writes the logging event to each connected client.
  181. /// </summary>
  182. /// <param name="loggingEvent">The event to log.</param>
  183. /// <remarks>
  184. /// <para>
  185. /// Writes the logging event to each connected client.
  186. /// </para>
  187. /// </remarks>
  188. protected override void Append(LoggingEvent loggingEvent)
  189. {
  190. if (m_handler != null && m_handler.HasConnections)
  191. {
  192. m_handler.Send(RenderLoggingEvent(loggingEvent));
  193. }
  194. }
  195. #endregion
  196. #region SocketHandler helper class
  197. /// <summary>
  198. /// Helper class to manage connected clients
  199. /// </summary>
  200. /// <remarks>
  201. /// <para>
  202. /// The SocketHandler class is used to accept connections from
  203. /// clients. It is threaded so that clients can connect/disconnect
  204. /// asynchronously.
  205. /// </para>
  206. /// </remarks>
  207. protected class SocketHandler : IDisposable
  208. {
  209. private const int MAX_CONNECTIONS = 20;
  210. private Socket m_serverSocket;
  211. private ArrayList m_clients = new ArrayList();
  212. /// <summary>
  213. /// Class that represents a client connected to this handler
  214. /// </summary>
  215. /// <remarks>
  216. /// <para>
  217. /// Class that represents a client connected to this handler
  218. /// </para>
  219. /// </remarks>
  220. protected class SocketClient : IDisposable
  221. {
  222. private Socket m_socket;
  223. private StreamWriter m_writer;
  224. /// <summary>
  225. /// Create this <see cref="SocketClient"/> for the specified <see cref="Socket"/>
  226. /// </summary>
  227. /// <param name="socket">the client's socket</param>
  228. /// <remarks>
  229. /// <para>
  230. /// Opens a stream writer on the socket.
  231. /// </para>
  232. /// </remarks>
  233. public SocketClient(Socket socket)
  234. {
  235. m_socket = socket;
  236. try
  237. {
  238. m_writer = new StreamWriter(new NetworkStream(socket));
  239. }
  240. catch
  241. {
  242. Dispose();
  243. throw;
  244. }
  245. }
  246. /// <summary>
  247. /// Write a string to the client
  248. /// </summary>
  249. /// <param name="message">string to send</param>
  250. /// <remarks>
  251. /// <para>
  252. /// Write a string to the client
  253. /// </para>
  254. /// </remarks>
  255. public void Send(String message)
  256. {
  257. m_writer.Write(message);
  258. m_writer.Flush();
  259. }
  260. #region IDisposable Members
  261. /// <summary>
  262. /// Cleanup the clients connection
  263. /// </summary>
  264. /// <remarks>
  265. /// <para>
  266. /// Close the socket connection.
  267. /// </para>
  268. /// </remarks>
  269. public void Dispose()
  270. {
  271. try
  272. {
  273. if (m_writer != null)
  274. {
  275. m_writer.Close();
  276. m_writer = null;
  277. }
  278. }
  279. catch { }
  280. if (m_socket != null)
  281. {
  282. try
  283. {
  284. m_socket.Shutdown(SocketShutdown.Both);
  285. }
  286. catch { }
  287. try
  288. {
  289. m_socket.Close();
  290. }
  291. catch { }
  292. m_socket = null;
  293. }
  294. }
  295. #endregion
  296. }
  297. /// <summary>
  298. /// Opens a new server port on <paramref ref="port"/>
  299. /// </summary>
  300. /// <param name="port">the local port to listen on for connections</param>
  301. /// <remarks>
  302. /// <para>
  303. /// Creates a socket handler on the specified local server port.
  304. /// </para>
  305. /// </remarks>
  306. public SocketHandler(int port)
  307. {
  308. m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  309. m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
  310. m_serverSocket.Listen(5);
  311. AcceptConnection();
  312. }
  313. private void AcceptConnection()
  314. {
  315. #if NETSTANDARD1_3
  316. m_serverSocket.AcceptAsync().ContinueWith(OnConnect, TaskScheduler.Default);
  317. #else
  318. m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null);
  319. #endif
  320. }
  321. /// <summary>
  322. /// Sends a string message to each of the connected clients
  323. /// </summary>
  324. /// <param name="message">the text to send</param>
  325. /// <remarks>
  326. /// <para>
  327. /// Sends a string message to each of the connected clients
  328. /// </para>
  329. /// </remarks>
  330. public void Send(String message)
  331. {
  332. ArrayList localClients = m_clients;
  333. foreach (SocketClient client in localClients)
  334. {
  335. try
  336. {
  337. client.Send(message);
  338. }
  339. catch (Exception)
  340. {
  341. // The client has closed the connection, remove it from our list
  342. client.Dispose();
  343. RemoveClient(client);
  344. }
  345. }
  346. }
  347. /// <summary>
  348. /// Add a client to the internal clients list
  349. /// </summary>
  350. /// <param name="client">client to add</param>
  351. private void AddClient(SocketClient client)
  352. {
  353. lock(this)
  354. {
  355. ArrayList clientsCopy = (ArrayList)m_clients.Clone();
  356. clientsCopy.Add(client);
  357. m_clients = clientsCopy;
  358. }
  359. }
  360. /// <summary>
  361. /// Remove a client from the internal clients list
  362. /// </summary>
  363. /// <param name="client">client to remove</param>
  364. private void RemoveClient(SocketClient client)
  365. {
  366. lock(this)
  367. {
  368. ArrayList clientsCopy = (ArrayList)m_clients.Clone();
  369. clientsCopy.Remove(client);
  370. m_clients = clientsCopy;
  371. }
  372. }
  373. /// <summary>
  374. /// Test if this handler has active connections
  375. /// </summary>
  376. /// <value>
  377. /// <c>true</c> if this handler has active connections
  378. /// </value>
  379. /// <remarks>
  380. /// <para>
  381. /// This property will be <c>true</c> while this handler has
  382. /// active connections, that is at least one connection that
  383. /// the handler will attempt to send a message to.
  384. /// </para>
  385. /// </remarks>
  386. public bool HasConnections
  387. {
  388. get
  389. {
  390. ArrayList localClients = m_clients;
  391. return (localClients != null && localClients.Count > 0);
  392. }
  393. }
  394. #if NETSTANDARD1_3
  395. private void OnConnect(Task<Socket> acceptTask)
  396. #else
  397. /// <summary>
  398. /// Callback used to accept a connection on the server socket
  399. /// </summary>
  400. /// <param name="asyncResult">The result of the asynchronous operation</param>
  401. /// <remarks>
  402. /// <para>
  403. /// On connection adds to the list of connections
  404. /// if there are two many open connections you will be disconnected
  405. /// </para>
  406. /// </remarks>
  407. private void OnConnect(IAsyncResult asyncResult)
  408. #endif
  409. {
  410. try
  411. {
  412. #if NETSTANDARD1_3
  413. Socket socket = acceptTask.GetAwaiter().GetResult();
  414. #else
  415. // Block until a client connects
  416. Socket socket = m_serverSocket.EndAccept(asyncResult);
  417. #endif
  418. LogLog.Debug(declaringType, "Accepting connection from ["+socket.RemoteEndPoint.ToString()+"]");
  419. SocketClient client = new SocketClient(socket);
  420. int currentActiveConnectionsCount = m_clients.Count;
  421. if (currentActiveConnectionsCount < MAX_CONNECTIONS)
  422. {
  423. try
  424. {
  425. client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n");
  426. AddClient(client);
  427. }
  428. catch
  429. {
  430. client.Dispose();
  431. }
  432. }
  433. else
  434. {
  435. client.Send("Sorry - Too many connections.\r\n");
  436. client.Dispose();
  437. }
  438. }
  439. catch
  440. {
  441. }
  442. finally
  443. {
  444. if (m_serverSocket != null)
  445. {
  446. AcceptConnection();
  447. }
  448. }
  449. }
  450. #region IDisposable Members
  451. /// <summary>
  452. /// Close all network connections
  453. /// </summary>
  454. /// <remarks>
  455. /// <para>
  456. /// Make sure we close all network connections
  457. /// </para>
  458. /// </remarks>
  459. public void Dispose()
  460. {
  461. ArrayList localClients = m_clients;
  462. foreach (SocketClient client in localClients)
  463. {
  464. client.Dispose();
  465. }
  466. m_clients.Clear();
  467. Socket localSocket = m_serverSocket;
  468. m_serverSocket = null;
  469. try
  470. {
  471. localSocket.Shutdown(SocketShutdown.Both);
  472. }
  473. catch
  474. {
  475. }
  476. try
  477. {
  478. localSocket.Close();
  479. }
  480. catch
  481. {
  482. }
  483. }
  484. #endregion
  485. }
  486. #endregion
  487. }
  488. }