Pop3Command.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading;
  7. namespace Ant.Service.Utilities
  8. {
  9. /// <summary>
  10. /// This class represents a generic Pop3 command and
  11. /// encapsulates the major operations when executing a
  12. /// Pop3 command against a Pop3 Server.
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. internal abstract class Pop3Command<T> : IDisposable where T : Pop3Response
  16. {
  17. public event Action<string> Trace;
  18. protected void OnTrace(string message)
  19. {
  20. if (Trace != null)
  21. {
  22. Trace(message);
  23. }
  24. }
  25. private const int BufferSize = 1024;
  26. private const string MultilineMessageTerminator = "\r\n.\r\n";
  27. private const string MessageTerminator = ".";
  28. private ManualResetEvent _manualResetEvent;
  29. private byte[] _buffer;
  30. private MemoryStream _responseContents;
  31. private Pop3State _validExecuteState;
  32. public Pop3State ValidExecuteState
  33. {
  34. get { return _validExecuteState; }
  35. }
  36. private Stream _networkStream;
  37. public Stream NetworkStream
  38. {
  39. get { return _networkStream; }
  40. set { _networkStream = value; }
  41. }
  42. bool _isMultiline;
  43. /// <summary>
  44. /// Sets a value indicating whether this instance is multiline.
  45. /// </summary>
  46. /// <value>
  47. /// <c>true</c> if this instance is multiline; otherwise, <c>false</c>.
  48. /// </value>
  49. protected bool IsMultiline
  50. {
  51. get
  52. {
  53. return _isMultiline;
  54. }
  55. set
  56. {
  57. _isMultiline = value;
  58. }
  59. }
  60. /// <summary>
  61. /// Initializes a new instance of the <see cref="Pop3CommandBase"/> class.
  62. /// </summary>
  63. /// <param name="stream">The stream.</param>
  64. /// <param name="isMultiline">if set to <c>true</c> [is multiline].</param>
  65. /// <param name="validExecuteState">State of the valid execute.</param>
  66. public Pop3Command(Stream stream, bool isMultiline, Pop3State validExecuteState)
  67. {
  68. if (stream == null)
  69. {
  70. throw new ArgumentNullException("stream");
  71. }
  72. _manualResetEvent = new ManualResetEvent(false);
  73. _buffer = new byte[BufferSize];
  74. _responseContents = new MemoryStream();
  75. _networkStream = stream;
  76. _isMultiline = isMultiline;
  77. _validExecuteState = validExecuteState;
  78. }
  79. /// <summary>
  80. /// Abstract method intended for inheritors to
  81. /// build out the byte[] request message for
  82. /// the specific command.
  83. /// </summary>
  84. /// <returns>The byte[] containing the request message.</returns>
  85. protected abstract byte[] CreateRequestMessage();
  86. /// <summary>
  87. /// Sends the specified message.
  88. /// </summary>
  89. /// <param name="message">The message.</param>
  90. private void Send(byte[] message)
  91. {
  92. //EnsureConnection();
  93. try
  94. {
  95. _networkStream.Write(message, 0, message.Length);
  96. }
  97. catch (SocketException e)
  98. {
  99. throw new Pop3Exception("Unable to send the request message: " + Encoding.ASCII.GetString(message), e);
  100. }
  101. }
  102. /// <summary>
  103. /// Executes this instance.
  104. /// </summary>
  105. /// <returns></returns>
  106. internal virtual T Execute(Pop3State currentState)
  107. {
  108. EnsurePop3State(currentState);
  109. byte[] message = CreateRequestMessage();
  110. if (message != null)
  111. {
  112. Send(message);
  113. }
  114. T response = CreateResponse(GetResponse());
  115. if (response == null)
  116. {
  117. return null;
  118. }
  119. OnTrace(response.HostMessage);
  120. return response;
  121. }
  122. /// <summary>
  123. /// Ensures the state of the POP3.
  124. /// </summary>
  125. /// <param name="currentState">State of the current.</param>
  126. protected void EnsurePop3State(Pop3State currentState)
  127. {
  128. if (!((currentState & ValidExecuteState) == currentState))
  129. {
  130. throw new Pop3Exception(string.Format("This command is being executed" +
  131. "in an invalid execution state. Current:{0}, Valid:{1}",
  132. currentState, ValidExecuteState));
  133. }
  134. }
  135. /// <summary>
  136. /// Creates the response.
  137. /// </summary>
  138. /// <param name="buffer">The buffer.</param>
  139. /// <returns>The <c>Pop3Response</c> containing the results of the
  140. /// Pop3 command execution.</returns>
  141. protected virtual T CreateResponse(byte[] buffer)
  142. {
  143. return Pop3Response.CreateResponse(buffer) as T;
  144. }
  145. /// <summary>
  146. /// Gets the response.
  147. /// </summary>
  148. /// <returns></returns>
  149. private byte[] GetResponse()
  150. {
  151. //EnsureConnection();
  152. AsyncCallback callback;
  153. if (_isMultiline)
  154. {
  155. callback = new AsyncCallback(GetMultiLineResponseCallback);
  156. }
  157. else
  158. {
  159. callback = new AsyncCallback(GetSingleLineResponseCallback);
  160. }
  161. try
  162. {
  163. Receive(callback);
  164. _manualResetEvent.WaitOne();
  165. return _responseContents.ToArray();
  166. }
  167. catch (SocketException e)
  168. {
  169. throw new Pop3Exception("Unable to get response.", e);
  170. }
  171. }
  172. /// <summary>
  173. /// Receives the specified callback.
  174. /// </summary>
  175. /// <param name="callback">The callback.</param>
  176. /// <returns></returns>
  177. private IAsyncResult Receive(AsyncCallback callback)
  178. {
  179. return _networkStream.BeginRead(_buffer, 0, _buffer.Length, callback, null);
  180. }
  181. /// <summary>
  182. /// Writes the received bytes to buffer.
  183. /// </summary>
  184. /// <param name="bytesReceived">The bytes received.</param>
  185. /// <returns></returns>
  186. private string WriteReceivedBytesToBuffer(int bytesReceived)
  187. {
  188. _responseContents.Write(_buffer, 0, bytesReceived);
  189. byte[] contents = _responseContents.ToArray();
  190. return Encoding.ASCII.GetString(contents, (contents.Length > 5 ? contents.Length - 5 : 0), 5);
  191. }
  192. /// <summary>
  193. /// Gets the single line response callback.
  194. /// </summary>
  195. /// <param name="ar">The ar.</param>
  196. private void GetSingleLineResponseCallback(IAsyncResult ar)
  197. {
  198. int bytesReceived = _networkStream.EndRead(ar);
  199. string message = WriteReceivedBytesToBuffer(bytesReceived);
  200. if (message.EndsWith(Pop3Commands.Crlf))
  201. {
  202. _manualResetEvent.Set();
  203. }
  204. else
  205. {
  206. Receive(new AsyncCallback(GetSingleLineResponseCallback));
  207. }
  208. }
  209. /// <summary>
  210. /// Gets the multi line response callback.
  211. /// </summary>
  212. /// <param name="ar">The ar.</param>
  213. private void GetMultiLineResponseCallback(IAsyncResult ar)
  214. {
  215. int bytesReceived = _networkStream.EndRead(ar);
  216. string message = WriteReceivedBytesToBuffer(bytesReceived);
  217. if (message.EndsWith(MultilineMessageTerminator)
  218. || bytesReceived == 0) //if the POP3 server times out we'll get an error message, then we'll get a following callback w/ 0 bytes.
  219. {
  220. _manualResetEvent.Set();
  221. }
  222. else
  223. {
  224. Receive(new AsyncCallback(GetMultiLineResponseCallback));
  225. }
  226. }
  227. /// <summary>
  228. /// Gets the request message.
  229. /// </summary>
  230. /// <param name="args">The args.</param>
  231. /// <returns>A byte[] request message to send to the host.</returns>
  232. protected byte[] GetRequestMessage(params string[] args)
  233. {
  234. string message = string.Join(string.Empty, args);
  235. OnTrace(message);
  236. return Encoding.ASCII.GetBytes(message);
  237. }
  238. /// <summary>
  239. /// Strips the POP3 host message.
  240. /// </summary>
  241. /// <param name="bytes">The bytes.</param>
  242. /// <param name="header">The header.</param>
  243. /// <returns>A <c>MemoryStream</c> without the Pop3 server message.</returns>
  244. protected MemoryStream StripPop3HostMessage(byte[] bytes, string header)
  245. {
  246. int position = header.Length + 2;
  247. MemoryStream stream = new MemoryStream(bytes, position, bytes.Length - position);
  248. return stream;
  249. }
  250. /// <summary>
  251. /// Gets the response lines.
  252. /// </summary>
  253. /// <param name="stream">The stream.</param>
  254. /// <returns>A string[] of Pop3 response lines.</returns>
  255. protected string[] GetResponseLines(MemoryStream stream)
  256. {
  257. List<string> lines = new List<string>();
  258. using (StreamReader reader = new StreamReader(stream))
  259. {
  260. try
  261. {
  262. string line;
  263. do
  264. {
  265. line = reader.ReadLine();
  266. //pop3 protocol states if a line starts w/ a
  267. //'.' that line will be byte stuffed w/ a '.'
  268. //if it is byte stuffed the remove the byte,
  269. //otherwise we have reached the end of the message.
  270. if (line.StartsWith(MessageTerminator))
  271. {
  272. if (line == MessageTerminator)
  273. {
  274. break;
  275. }
  276. line = line.Substring(1);
  277. }
  278. lines.Add(line);
  279. } while (true);
  280. }
  281. catch (IOException e)
  282. {
  283. throw new Pop3Exception("Unable to get response lines.", e);
  284. }
  285. return lines.ToArray();
  286. }
  287. }
  288. public void Dispose()
  289. {
  290. if (_responseContents != null)
  291. {
  292. _responseContents.Dispose();
  293. }
  294. }
  295. }
  296. }