MultipartFormDataStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Best.HTTP.Hosts.Connections;
  5. using Best.HTTP.Shared.Extensions;
  6. using Best.HTTP.Shared.PlatformSupport.Memory;
  7. using Best.HTTP.Shared.Streams;
  8. using UnityEngine;
  9. using static Best.HTTP.Hosts.Connections.HTTP1.Constants;
  10. namespace Best.HTTP.Request.Upload.Forms
  11. {
  12. /// <summary>
  13. /// An <see cref="UploadStreamBase"/> based implementation of the <c>multipart/form-data</c> Content-Type. It's very memory-effective, streams are read into memory in chunks.
  14. /// </summary>
  15. /// <remarks>
  16. /// <para>The return value of <see cref="System.IO.Stream.Read(byte[], int, int)"/> is treated specially in the plugin:
  17. /// <list type="bullet">
  18. /// <item>
  19. /// <term>Less than zero(<c>-1</c>) value </term>
  20. /// <description> indicates that no data is currently available but more is expected in the future. In this case, when new data becomes available the IThreadSignaler object must be signaled.</description>
  21. /// </item>
  22. /// <item>
  23. /// <term>Zero (<c>0</c>)</term>
  24. /// <description> means that the stream is closed, no more data can be expected.</description>
  25. /// </item>
  26. /// </list>
  27. /// A zero value to signal stream closure can follow a less than zero value.</para>
  28. /// </remarks>
  29. public sealed class MultipartFormDataStream : UploadStreamBase
  30. {
  31. /// <summary>
  32. /// Gets the length of this multipart/form-data stream.
  33. /// </summary>
  34. public override long Length { get => this._length; }
  35. private long _length;
  36. /// <summary>
  37. /// A random boundary generated in the constructor.
  38. /// </summary>
  39. private string boundary;
  40. private Queue<StreamList> fields = new Queue<StreamList>(1);
  41. private StreamList currentField;
  42. /// <summary>
  43. /// Initializes a new instance of the MultipartFormDataStream class.
  44. /// </summary>
  45. public MultipartFormDataStream()
  46. {
  47. var hash = new Hash128();
  48. hash.Append(this.GetHashCode());
  49. this.boundary = $"com.Tivadar.Best.HTTP.boundary.{hash}";
  50. }
  51. /// <summary>
  52. /// Initializes a new instance of the MultipartFormDataStream class with a custom boundary.
  53. /// </summary>
  54. public MultipartFormDataStream(string boundary)
  55. {
  56. this.boundary = boundary;
  57. }
  58. public override void BeforeSendHeaders(HTTPRequest request)
  59. {
  60. request.SetHeader("Content-Type", $"multipart/form-data; boundary=\"{this.boundary}\"");
  61. var boundaryStream = new BufferPoolMemoryStream();
  62. boundaryStream.WriteLine("--" + this.boundary + "--");
  63. boundaryStream.Position = 0;
  64. this.fields.Enqueue(new StreamList(boundaryStream));
  65. if (this._length >= 0)
  66. this._length += boundaryStream.Length;
  67. }
  68. /// <summary>
  69. /// Adds a textual field to the multipart/form-data stream.
  70. /// </summary>
  71. /// <param name="fieldName">The name of the field.</param>
  72. /// <param name="value">The textual value of the field.</param>
  73. /// <returns>The MultipartFormDataStream instance for method chaining.</returns>
  74. public MultipartFormDataStream AddField(string fieldName, string value)
  75. => AddField(fieldName, value, System.Text.Encoding.UTF8);
  76. /// <summary>
  77. /// Adds a textual field to the multipart/form-data stream.
  78. /// </summary>
  79. /// <param name="fieldName">The name of the field.</param>
  80. /// <param name="value">The textual value of the field.</param>
  81. /// <param name="encoding">The encoding to use for the value.</param>
  82. /// <returns>The MultipartFormDataStream instance for method chaining.</returns>
  83. public MultipartFormDataStream AddField(string fieldName, string value, System.Text.Encoding encoding)
  84. {
  85. var enc = encoding ?? System.Text.Encoding.UTF8;
  86. var byteCount = enc.GetByteCount(value);
  87. var buffer = BufferPool.Get(byteCount, true);
  88. var stream = new BufferPoolMemoryStream();
  89. enc.GetBytes(value, 0, value.Length, buffer, 0);
  90. stream.Write(buffer, 0, byteCount);
  91. stream.Position = 0;
  92. string mime = encoding != null ? "text/plain; charset=" + encoding.WebName : null;
  93. return AddStreamField(fieldName, stream, null, mime);
  94. }
  95. /// <summary>
  96. /// Adds a stream field to the multipart/form-data stream.
  97. /// </summary>
  98. /// <param name="fieldName">The name of the field.</param>
  99. /// <param name="data">The data containing the field data.</param>
  100. /// <returns>The MultipartFormDataStream instance for method chaining.</returns>
  101. public MultipartFormDataStream AddField(string fieldName, byte[] data)
  102. => AddStreamField(fieldName, new MemoryStream(data));
  103. /// <summary>
  104. /// Adds a stream field to the multipart/form-data stream.
  105. /// </summary>
  106. /// <param name="stream">The stream containing the field data.</param>
  107. /// <param name="fieldName">The name of the field.</param>
  108. /// <returns>The MultipartFormDataStream instance for method chaining.</returns>
  109. public MultipartFormDataStream AddStreamField(string fieldName, System.IO.Stream stream)
  110. => AddStreamField(fieldName, stream, null, null);
  111. /// <summary>
  112. /// Adds a stream field to the multipart/form-data stream.
  113. /// </summary>
  114. /// <param name="stream">The stream containing the field data.</param>
  115. /// <param name="fieldName">The name of the field.</param>
  116. /// <param name="fileName">The name of the file, if applicable.</param>
  117. /// <returns>The MultipartFormDataStream instance for method chaining.</returns>
  118. public MultipartFormDataStream AddStreamField(string fieldName, System.IO.Stream stream, string fileName)
  119. => AddStreamField(fieldName, stream, fileName, null);
  120. /// <summary>
  121. /// Adds a stream field to the multipart/form-data stream.
  122. /// </summary>
  123. /// <param name="stream">The stream containing the field data.</param>
  124. /// <param name="fieldName">The name of the field.</param>
  125. /// <param name="fileName">The name of the file, if applicable.</param>
  126. /// <param name="mimeType">The MIME type of the content.</param>
  127. /// <returns>The MultipartFormDataStream instance for method chaining.</returns>
  128. public MultipartFormDataStream AddStreamField(string fieldName, System.IO.Stream stream, string fileName, string mimeType)
  129. {
  130. var header = new BufferPoolMemoryStream();
  131. header.WriteLine("--" + this.boundary);
  132. header.WriteLine("Content-Disposition: form-data; name=\"" + fieldName + "\"" + (!string.IsNullOrEmpty(fileName) ? "; filename=\"" + fileName + "\"" : string.Empty));
  133. // Set up Content-Type head for the form.
  134. if (!string.IsNullOrEmpty(mimeType))
  135. header.WriteLine("Content-Type: " + mimeType);
  136. header.WriteLine();
  137. header.Position = 0;
  138. var footer = new BufferPoolMemoryStream();
  139. footer.Write(EOL, 0, EOL.Length);
  140. footer.Position = 0;
  141. // all wrapped streams going to be disposed by the StreamList wrapper.
  142. var wrapper = new StreamList(header, stream, footer);
  143. try
  144. {
  145. if (this._length >= 0)
  146. this._length += wrapper.Length;
  147. }
  148. catch
  149. {
  150. this._length = -1;
  151. }
  152. this.fields.Enqueue(wrapper);
  153. return this;
  154. }
  155. /// <summary>
  156. /// Adds the final boundary to the multipart/form-data stream before sending the request body.
  157. /// </summary>
  158. /// <param name="request">The HTTP request.</param>
  159. /// <param name="threadSignaler">The thread signaler for handling asynchronous operations.</param>
  160. public override void BeforeSendBody(HTTPRequest request, IThreadSignaler threadSignaler)
  161. {
  162. base.BeforeSendBody(request, threadSignaler);
  163. }
  164. /// <summary>
  165. /// Reads data from the multipart/form-data stream into the provided buffer.
  166. /// </summary>
  167. /// <param name="buffer">The buffer to read data into.</param>
  168. /// <param name="offset">The starting offset in the buffer.</param>
  169. /// <param name="length">The maximum number of bytes to read.</param>
  170. /// <returns>The number of bytes read into the buffer.</returns>
  171. public override int Read(byte[] buffer, int offset, int length)
  172. {
  173. if (this.currentField == null && this.fields.Count == 0)
  174. return -1;
  175. if (this.currentField == null && this.fields.Count > 0)
  176. this.currentField = this.fields.Dequeue();
  177. int readCount = 0;
  178. do
  179. {
  180. // read from the current stream
  181. int count = this.currentField.Read(buffer, offset + readCount, length - readCount);
  182. if (count > 0)
  183. readCount += count;
  184. else
  185. {
  186. // if the current field's stream is empty, go for the next one.
  187. // dispose the current one first
  188. try
  189. {
  190. this.currentField.Dispose();
  191. }
  192. catch
  193. { }
  194. // no more fields/streams? exit
  195. if (this.fields.Count == 0)
  196. break;
  197. // grab the next one
  198. this.currentField = this.fields.Dequeue();
  199. }
  200. // exit when we reach the length goal, or there's no more streams to read from
  201. } while (readCount < length && this.fields.Count > 0);
  202. return readCount;
  203. }
  204. protected override void Dispose(bool disposing)
  205. {
  206. base.Dispose(disposing);
  207. if (fields != null)
  208. {
  209. foreach (var field in fields)
  210. field.Dispose();
  211. fields.Clear();
  212. fields = null;
  213. }
  214. currentField?.Dispose();
  215. currentField = null;
  216. }
  217. public override bool CanRead { get { return true; } }
  218. public override bool CanSeek { get { return false; } }
  219. public override bool CanWrite { get { return false; } }
  220. public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
  221. public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();
  222. public override void SetLength(long value) => throw new NotImplementedException();
  223. public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
  224. public override void Flush() { }
  225. }
  226. }