You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

807 lines
31 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2010, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #ifndef TALK_BASE_STREAM_H_
  28. #define TALK_BASE_STREAM_H_
  29. #include "talk/base/basictypes.h"
  30. #include "talk/base/buffer.h"
  31. #include "talk/base/criticalsection.h"
  32. #include "talk/base/logging.h"
  33. #include "talk/base/messagehandler.h"
  34. #include "talk/base/messagequeue.h"
  35. #include "talk/base/scoped_ptr.h"
  36. #include "talk/base/sigslot.h"
  37. namespace talk_base {
  38. ///////////////////////////////////////////////////////////////////////////////
  39. // StreamInterface is a generic asynchronous stream interface, supporting read,
  40. // write, and close operations, and asynchronous signalling of state changes.
  41. // The interface is designed with file, memory, and socket implementations in
  42. // mind. Some implementations offer extended operations, such as seeking.
  43. ///////////////////////////////////////////////////////////////////////////////
  44. // The following enumerations are declared outside of the StreamInterface
  45. // class for brevity in use.
  46. // The SS_OPENING state indicates that the stream will signal open or closed
  47. // in the future.
  48. enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
  49. // Stream read/write methods return this value to indicate various success
  50. // and failure conditions described below.
  51. enum StreamResult { SR_ERROR, SR_SUCCESS, SR_BLOCK, SR_EOS };
  52. // StreamEvents are used to asynchronously signal state transitionss. The flags
  53. // may be combined.
  54. // SE_OPEN: The stream has transitioned to the SS_OPEN state
  55. // SE_CLOSE: The stream has transitioned to the SS_CLOSED state
  56. // SE_READ: Data is available, so Read is likely to not return SR_BLOCK
  57. // SE_WRITE: Data can be written, so Write is likely to not return SR_BLOCK
  58. enum StreamEvent { SE_OPEN = 1, SE_READ = 2, SE_WRITE = 4, SE_CLOSE = 8 };
  59. class Thread;
  60. struct StreamEventData : public MessageData {
  61. int events, error;
  62. StreamEventData(int ev, int er) : events(ev), error(er) { }
  63. };
  64. class StreamInterface : public MessageHandler {
  65. public:
  66. enum {
  67. MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
  68. };
  69. virtual ~StreamInterface();
  70. virtual StreamState GetState() const = 0;
  71. // Read attempts to fill buffer of size buffer_len. Write attempts to send
  72. // data_len bytes stored in data. The variables read and write are set only
  73. // on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
  74. // Read and Write return a value indicating:
  75. // SR_ERROR: an error occurred, which is returned in a non-null error
  76. // argument. Interpretation of the error requires knowledge of the
  77. // stream's concrete type, which limits its usefulness.
  78. // SR_SUCCESS: some number of bytes were successfully written, which is
  79. // returned in a non-null read/write argument.
  80. // SR_BLOCK: the stream is in non-blocking mode, and the operation would
  81. // block, or the stream is in SS_OPENING state.
  82. // SR_EOS: the end-of-stream has been reached, or the stream is in the
  83. // SS_CLOSED state.
  84. virtual StreamResult Read(void* buffer, size_t buffer_len,
  85. size_t* read, int* error) = 0;
  86. virtual StreamResult Write(const void* data, size_t data_len,
  87. size_t* written, int* error) = 0;
  88. // Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
  89. // signalled as a result of this call.
  90. virtual void Close() = 0;
  91. // Streams may signal one or more StreamEvents to indicate state changes.
  92. // The first argument identifies the stream on which the state change occured.
  93. // The second argument is a bit-wise combination of StreamEvents.
  94. // If SE_CLOSE is signalled, then the third argument is the associated error
  95. // code. Otherwise, the value is undefined.
  96. // Note: Not all streams will support asynchronous event signalling. However,
  97. // SS_OPENING and SR_BLOCK returned from stream member functions imply that
  98. // certain events will be raised in the future.
  99. sigslot::signal3<StreamInterface*, int, int> SignalEvent;
  100. // Like calling SignalEvent, but posts a message to the specified thread,
  101. // which will call SignalEvent. This helps unroll the stack and prevent
  102. // re-entrancy.
  103. void PostEvent(Thread* t, int events, int err);
  104. // Like the aforementioned method, but posts to the current thread.
  105. void PostEvent(int events, int err);
  106. //
  107. // OPTIONAL OPERATIONS
  108. //
  109. // Not all implementations will support the following operations. In general,
  110. // a stream will only support an operation if it reasonably efficient to do
  111. // so. For example, while a socket could buffer incoming data to support
  112. // seeking, it will not do so. Instead, a buffering stream adapter should
  113. // be used.
  114. //
  115. // Even though several of these operations are related, you should
  116. // always use whichever operation is most relevant. For example, you may
  117. // be tempted to use GetSize() and GetPosition() to deduce the result of
  118. // GetAvailable(). However, a stream which is read-once may support the
  119. // latter operation but not the former.
  120. //
  121. // The following four methods are used to avoid copying data multiple times.
  122. // GetReadData returns a pointer to a buffer which is owned by the stream.
  123. // The buffer contains data_len bytes. NULL is returned if no data is
  124. // available, or if the method fails. If the caller processes the data, it
  125. // must call ConsumeReadData with the number of processed bytes. GetReadData
  126. // does not require a matching call to ConsumeReadData if the data is not
  127. // processed. Read and ConsumeReadData invalidate the buffer returned by
  128. // GetReadData.
  129. virtual const void* GetReadData(size_t* data_len) { return NULL; }
  130. virtual void ConsumeReadData(size_t used) {}
  131. // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
  132. // The buffer has a capacity of buf_len bytes. NULL is returned if there is
  133. // no buffer available, or if the method fails. The call may write data to
  134. // the buffer, and then call ConsumeWriteBuffer with the number of bytes
  135. // written. GetWriteBuffer does not require a matching call to
  136. // ConsumeWriteData if no data is written. Write, ForceWrite, and
  137. // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
  138. // TODO: Allow the caller to specify a minimum buffer size. If the specified
  139. // amount of buffer is not yet available, return NULL and Signal SE_WRITE
  140. // when it is available. If the requested amount is too large, return an
  141. // error.
  142. virtual void* GetWriteBuffer(size_t* buf_len) { return NULL; }
  143. virtual void ConsumeWriteBuffer(size_t used) {}
  144. // Write data_len bytes found in data, circumventing any throttling which
  145. // would could cause SR_BLOCK to be returned. Returns true if all the data
  146. // was written. Otherwise, the method is unsupported, or an unrecoverable
  147. // error occurred, and the error value is set. This method should be used
  148. // sparingly to write critical data which should not be throttled. A stream
  149. // which cannot circumvent its blocking constraints should not implement this
  150. // method.
  151. // NOTE: This interface is being considered experimentally at the moment. It
  152. // would be used by JUDP and BandwidthStream as a way to circumvent certain
  153. // soft limits in writing.
  154. //virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
  155. // if (error) *error = -1;
  156. // return false;
  157. //}
  158. // Seek to a byte offset from the beginning of the stream. Returns false if
  159. // the stream does not support seeking, or cannot seek to the specified
  160. // position.
  161. virtual bool SetPosition(size_t position) { return false; }
  162. // Get the byte offset of the current position from the start of the stream.
  163. // Returns false if the position is not known.
  164. virtual bool GetPosition(size_t* position) const { return false; }
  165. // Get the byte length of the entire stream. Returns false if the length
  166. // is not known.
  167. virtual bool GetSize(size_t* size) const { return false; }
  168. // Return the number of Read()-able bytes remaining before end-of-stream.
  169. // Returns false if not known.
  170. virtual bool GetAvailable(size_t* size) const { return false; }
  171. // Return the number of Write()-able bytes remaining before end-of-stream.
  172. // Returns false if not known.
  173. virtual bool GetWriteRemaining(size_t* size) const { return false; }
  174. // Return true if flush is successful.
  175. virtual bool Flush() { return false; }
  176. // Communicates the amount of data which will be written to the stream. The
  177. // stream may choose to preallocate memory to accomodate this data. The
  178. // stream may return false to indicate that there is not enough room (ie,
  179. // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
  180. // function should not affect the existing state of data in the stream.
  181. virtual bool ReserveSize(size_t size) { return true; }
  182. //
  183. // CONVENIENCE METHODS
  184. //
  185. // These methods are implemented in terms of other methods, for convenience.
  186. //
  187. // Seek to the start of the stream.
  188. inline bool Rewind() { return SetPosition(0); }
  189. // WriteAll is a helper function which repeatedly calls Write until all the
  190. // data is written, or something other than SR_SUCCESS is returned. Note that
  191. // unlike Write, the argument 'written' is always set, and may be non-zero
  192. // on results other than SR_SUCCESS. The remaining arguments have the
  193. // same semantics as Write.
  194. StreamResult WriteAll(const void* data, size_t data_len,
  195. size_t* written, int* error);
  196. // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
  197. // until a non-SR_SUCCESS result is returned. 'read' is always set.
  198. StreamResult ReadAll(void* buffer, size_t buffer_len,
  199. size_t* read, int* error);
  200. // ReadLine is a helper function which repeatedly calls Read until it hits
  201. // the end-of-line character, or something other than SR_SUCCESS.
  202. // TODO: this is too inefficient to keep here. Break this out into a buffered
  203. // readline object or adapter
  204. StreamResult ReadLine(std::string* line);
  205. protected:
  206. StreamInterface();
  207. // MessageHandler Interface
  208. virtual void OnMessage(Message* msg);
  209. private:
  210. DISALLOW_EVIL_CONSTRUCTORS(StreamInterface);
  211. };
  212. ///////////////////////////////////////////////////////////////////////////////
  213. // StreamAdapterInterface is a convenient base-class for adapting a stream.
  214. // By default, all operations are pass-through. Override the methods that you
  215. // require adaptation. Streams should really be upgraded to reference-counted.
  216. // In the meantime, use the owned flag to indicate whether the adapter should
  217. // own the adapted stream.
  218. ///////////////////////////////////////////////////////////////////////////////
  219. class StreamAdapterInterface : public StreamInterface,
  220. public sigslot::has_slots<> {
  221. public:
  222. explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
  223. // Core Stream Interface
  224. virtual StreamState GetState() const {
  225. return stream_->GetState();
  226. }
  227. virtual StreamResult Read(void* buffer, size_t buffer_len,
  228. size_t* read, int* error) {
  229. return stream_->Read(buffer, buffer_len, read, error);
  230. }
  231. virtual StreamResult Write(const void* data, size_t data_len,
  232. size_t* written, int* error) {
  233. return stream_->Write(data, data_len, written, error);
  234. }
  235. virtual void Close() {
  236. stream_->Close();
  237. }
  238. // Optional Stream Interface
  239. /* Note: Many stream adapters were implemented prior to this Read/Write
  240. interface. Therefore, a simple pass through of data in those cases may
  241. be broken. At a later time, we should do a once-over pass of all
  242. adapters, and make them compliant with these interfaces, after which this
  243. code can be uncommented.
  244. virtual const void* GetReadData(size_t* data_len) {
  245. return stream_->GetReadData(data_len);
  246. }
  247. virtual void ConsumeReadData(size_t used) {
  248. stream_->ConsumeReadData(used);
  249. }
  250. virtual void* GetWriteBuffer(size_t* buf_len) {
  251. return stream_->GetWriteBuffer(buf_len);
  252. }
  253. virtual void ConsumeWriteBuffer(size_t used) {
  254. stream_->ConsumeWriteBuffer(used);
  255. }
  256. */
  257. /* Note: This interface is currently undergoing evaluation.
  258. virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
  259. return stream_->ForceWrite(data, data_len, error);
  260. }
  261. */
  262. virtual bool SetPosition(size_t position) {
  263. return stream_->SetPosition(position);
  264. }
  265. virtual bool GetPosition(size_t* position) const {
  266. return stream_->GetPosition(position);
  267. }
  268. virtual bool GetSize(size_t* size) const {
  269. return stream_->GetSize(size);
  270. }
  271. virtual bool GetAvailable(size_t* size) const {
  272. return stream_->GetAvailable(size);
  273. }
  274. virtual bool GetWriteRemaining(size_t* size) const {
  275. return stream_->GetWriteRemaining(size);
  276. }
  277. virtual bool ReserveSize(size_t size) {
  278. return stream_->ReserveSize(size);
  279. }
  280. virtual bool Flush() {
  281. return stream_->Flush();
  282. }
  283. void Attach(StreamInterface* stream, bool owned = true);
  284. StreamInterface* Detach();
  285. protected:
  286. virtual ~StreamAdapterInterface();
  287. // Note that the adapter presents itself as the origin of the stream events,
  288. // since users of the adapter may not recognize the adapted object.
  289. virtual void OnEvent(StreamInterface* stream, int events, int err) {
  290. SignalEvent(this, events, err);
  291. }
  292. StreamInterface* stream() { return stream_; }
  293. private:
  294. StreamInterface* stream_;
  295. bool owned_;
  296. DISALLOW_EVIL_CONSTRUCTORS(StreamAdapterInterface);
  297. };
  298. ///////////////////////////////////////////////////////////////////////////////
  299. // StreamTap is a non-modifying, pass-through adapter, which copies all data
  300. // in either direction to the tap. Note that errors or blocking on writing to
  301. // the tap will prevent further tap writes from occurring.
  302. ///////////////////////////////////////////////////////////////////////////////
  303. class StreamTap : public StreamAdapterInterface {
  304. public:
  305. explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
  306. void AttachTap(StreamInterface* tap);
  307. StreamInterface* DetachTap();
  308. StreamResult GetTapResult(int* error);
  309. // StreamAdapterInterface Interface
  310. virtual StreamResult Read(void* buffer, size_t buffer_len,
  311. size_t* read, int* error);
  312. virtual StreamResult Write(const void* data, size_t data_len,
  313. size_t* written, int* error);
  314. private:
  315. scoped_ptr<StreamInterface> tap_;
  316. StreamResult tap_result_;
  317. int tap_error_;
  318. DISALLOW_EVIL_CONSTRUCTORS(StreamTap);
  319. };
  320. ///////////////////////////////////////////////////////////////////////////////
  321. // StreamSegment adapts a read stream, to expose a subset of the adapted
  322. // stream's data. This is useful for cases where a stream contains multiple
  323. // documents concatenated together. StreamSegment can expose a subset of
  324. // the data as an independent stream, including support for rewinding and
  325. // seeking.
  326. ///////////////////////////////////////////////////////////////////////////////
  327. class StreamSegment : public StreamAdapterInterface {
  328. public:
  329. // The current position of the adapted stream becomes the beginning of the
  330. // segment. If a length is specified, it bounds the length of the segment.
  331. explicit StreamSegment(StreamInterface* stream);
  332. explicit StreamSegment(StreamInterface* stream, size_t length);
  333. // StreamAdapterInterface Interface
  334. virtual StreamResult Read(void* buffer, size_t buffer_len,
  335. size_t* read, int* error);
  336. virtual bool SetPosition(size_t position);
  337. virtual bool GetPosition(size_t* position) const;
  338. virtual bool GetSize(size_t* size) const;
  339. virtual bool GetAvailable(size_t* size) const;
  340. private:
  341. size_t start_, pos_, length_;
  342. DISALLOW_EVIL_CONSTRUCTORS(StreamSegment);
  343. };
  344. ///////////////////////////////////////////////////////////////////////////////
  345. // NullStream gives errors on read, and silently discards all written data.
  346. ///////////////////////////////////////////////////////////////////////////////
  347. class NullStream : public StreamInterface {
  348. public:
  349. NullStream();
  350. virtual ~NullStream();
  351. // StreamInterface Interface
  352. virtual StreamState GetState() const;
  353. virtual StreamResult Read(void* buffer, size_t buffer_len,
  354. size_t* read, int* error);
  355. virtual StreamResult Write(const void* data, size_t data_len,
  356. size_t* written, int* error);
  357. virtual void Close();
  358. };
  359. ///////////////////////////////////////////////////////////////////////////////
  360. // FileStream is a simple implementation of a StreamInterface, which does not
  361. // support asynchronous notification.
  362. ///////////////////////////////////////////////////////////////////////////////
  363. class FileStream : public StreamInterface {
  364. public:
  365. FileStream();
  366. virtual ~FileStream();
  367. // The semantics of filename and mode are the same as stdio's fopen
  368. virtual bool Open(const std::string& filename, const char* mode, int* error);
  369. virtual bool OpenShare(const std::string& filename, const char* mode,
  370. int shflag, int* error);
  371. // By default, reads and writes are buffered for efficiency. Disabling
  372. // buffering causes writes to block until the bytes on disk are updated.
  373. virtual bool DisableBuffering();
  374. virtual StreamState GetState() const;
  375. virtual StreamResult Read(void* buffer, size_t buffer_len,
  376. size_t* read, int* error);
  377. virtual StreamResult Write(const void* data, size_t data_len,
  378. size_t* written, int* error);
  379. virtual void Close();
  380. virtual bool SetPosition(size_t position);
  381. virtual bool GetPosition(size_t* position) const;
  382. virtual bool GetSize(size_t* size) const;
  383. virtual bool GetAvailable(size_t* size) const;
  384. virtual bool ReserveSize(size_t size);
  385. virtual bool Flush();
  386. #if defined(POSIX)
  387. // Tries to aquire an exclusive lock on the file.
  388. // Use OpenShare(...) on win32 to get similar functionality.
  389. bool TryLock();
  390. bool Unlock();
  391. #endif
  392. // Note: Deprecated in favor of Filesystem::GetFileSize().
  393. static bool GetSize(const std::string& filename, size_t* size);
  394. protected:
  395. virtual void DoClose();
  396. FILE* file_;
  397. private:
  398. DISALLOW_EVIL_CONSTRUCTORS(FileStream);
  399. };
  400. // A stream which pushes writes onto a separate thread and
  401. // returns from the write call immediately.
  402. class AsyncWriteStream : public StreamInterface {
  403. public:
  404. // Takes ownership of the stream, but not the thread.
  405. AsyncWriteStream(StreamInterface* stream, talk_base::Thread* write_thread)
  406. : stream_(stream),
  407. write_thread_(write_thread),
  408. state_(stream ? stream->GetState() : SS_CLOSED) {
  409. }
  410. virtual ~AsyncWriteStream();
  411. // StreamInterface Interface
  412. virtual StreamState GetState() const { return state_; }
  413. // This is needed by some stream writers, such as RtpDumpWriter.
  414. virtual bool GetPosition(size_t* position) const;
  415. virtual StreamResult Read(void* buffer, size_t buffer_len,
  416. size_t* read, int* error);
  417. virtual StreamResult Write(const void* data, size_t data_len,
  418. size_t* written, int* error);
  419. virtual void Close();
  420. virtual bool Flush();
  421. protected:
  422. // From MessageHandler
  423. virtual void OnMessage(talk_base::Message* pmsg);
  424. virtual void ClearBufferAndWrite();
  425. private:
  426. talk_base::scoped_ptr<StreamInterface> stream_;
  427. Thread* write_thread_;
  428. StreamState state_;
  429. Buffer buffer_;
  430. mutable CriticalSection crit_stream_;
  431. CriticalSection crit_buffer_;
  432. DISALLOW_EVIL_CONSTRUCTORS(AsyncWriteStream);
  433. };
  434. #ifdef POSIX
  435. // A FileStream that is actually not a file, but the output or input of a
  436. // sub-command. See "man 3 popen" for documentation of the underlying OS popen()
  437. // function.
  438. class POpenStream : public FileStream {
  439. public:
  440. POpenStream() : wait_status_(-1) {}
  441. virtual ~POpenStream();
  442. virtual bool Open(const std::string& subcommand, const char* mode,
  443. int* error);
  444. // Same as Open(). shflag is ignored.
  445. virtual bool OpenShare(const std::string& subcommand, const char* mode,
  446. int shflag, int* error);
  447. // Returns the wait status from the last Close() of an Open()'ed stream, or
  448. // -1 if no Open()+Close() has been done on this object. Meaning of the number
  449. // is documented in "man 2 wait".
  450. int GetWaitStatus() const { return wait_status_; }
  451. protected:
  452. virtual void DoClose();
  453. private:
  454. int wait_status_;
  455. };
  456. #endif // POSIX
  457. ///////////////////////////////////////////////////////////////////////////////
  458. // MemoryStream is a simple implementation of a StreamInterface over in-memory
  459. // data. Data is read and written at the current seek position. Reads return
  460. // end-of-stream when they reach the end of data. Writes actually extend the
  461. // end of data mark.
  462. ///////////////////////////////////////////////////////////////////////////////
  463. class MemoryStreamBase : public StreamInterface {
  464. public:
  465. virtual StreamState GetState() const;
  466. virtual StreamResult Read(void* buffer, size_t bytes, size_t* bytes_read,
  467. int* error);
  468. virtual StreamResult Write(const void* buffer, size_t bytes,
  469. size_t* bytes_written, int* error);
  470. virtual void Close();
  471. virtual bool SetPosition(size_t position);
  472. virtual bool GetPosition(size_t* position) const;
  473. virtual bool GetSize(size_t* size) const;
  474. virtual bool GetAvailable(size_t* size) const;
  475. virtual bool ReserveSize(size_t size);
  476. char* GetBuffer() { return buffer_; }
  477. const char* GetBuffer() const { return buffer_; }
  478. protected:
  479. MemoryStreamBase();
  480. virtual StreamResult DoReserve(size_t size, int* error);
  481. // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
  482. char* buffer_;
  483. size_t buffer_length_;
  484. size_t data_length_;
  485. size_t seek_position_;
  486. private:
  487. DISALLOW_EVIL_CONSTRUCTORS(MemoryStreamBase);
  488. };
  489. // MemoryStream dynamically resizes to accomodate written data.
  490. class MemoryStream : public MemoryStreamBase {
  491. public:
  492. MemoryStream();
  493. explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
  494. MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
  495. virtual ~MemoryStream();
  496. void SetData(const void* data, size_t length);
  497. protected:
  498. virtual StreamResult DoReserve(size_t size, int* error);
  499. // Memory Streams are aligned for efficiency.
  500. static const int kAlignment = 16;
  501. char* buffer_alloc_;
  502. };
  503. // ExternalMemoryStream adapts an external memory buffer, so writes which would
  504. // extend past the end of the buffer will return end-of-stream.
  505. class ExternalMemoryStream : public MemoryStreamBase {
  506. public:
  507. ExternalMemoryStream();
  508. ExternalMemoryStream(void* data, size_t length);
  509. virtual ~ExternalMemoryStream();
  510. void SetData(void* data, size_t length);
  511. };
  512. // FifoBuffer allows for efficient, thread-safe buffering of data between
  513. // writer and reader. As the data can wrap around the end of the buffer,
  514. // MemoryStreamBase can't help us here.
  515. class FifoBuffer : public StreamInterface {
  516. public:
  517. // Creates a FIFO buffer with the specified capacity.
  518. explicit FifoBuffer(size_t length);
  519. // Creates a FIFO buffer with the specified capacity and owner
  520. FifoBuffer(size_t length, Thread* owner);
  521. virtual ~FifoBuffer();
  522. // Gets the amount of data currently readable from the buffer.
  523. bool GetBuffered(size_t* data_len) const;
  524. // Resizes the buffer to the specified capacity. Fails if data_length_ > size
  525. bool SetCapacity(size_t length);
  526. // Read into |buffer| with an offset from the current read position, offset
  527. // is specified in number of bytes.
  528. // This method doesn't adjust read position nor the number of available
  529. // bytes, user has to call ConsumeReadData() to do this.
  530. StreamResult ReadOffset(void* buffer, size_t bytes, size_t offset,
  531. size_t* bytes_read);
  532. // Write |buffer| with an offset from the current write position, offset is
  533. // specified in number of bytes.
  534. // This method doesn't adjust the number of buffered bytes, user has to call
  535. // ConsumeWriteBuffer() to do this.
  536. StreamResult WriteOffset(const void* buffer, size_t bytes, size_t offset,
  537. size_t* bytes_written);
  538. // StreamInterface methods
  539. virtual StreamState GetState() const;
  540. virtual StreamResult Read(void* buffer, size_t bytes,
  541. size_t* bytes_read, int* error);
  542. virtual StreamResult Write(const void* buffer, size_t bytes,
  543. size_t* bytes_written, int* error);
  544. virtual void Close();
  545. virtual const void* GetReadData(size_t* data_len);
  546. virtual void ConsumeReadData(size_t used);
  547. virtual void* GetWriteBuffer(size_t* buf_len);
  548. virtual void ConsumeWriteBuffer(size_t used);
  549. virtual bool GetWriteRemaining(size_t* size) const;
  550. private:
  551. // Helper method that implements ReadOffset. Caller must acquire a lock
  552. // when calling this method.
  553. StreamResult ReadOffsetLocked(void* buffer, size_t bytes, size_t offset,
  554. size_t* bytes_read);
  555. // Helper method that implements WriteOffset. Caller must acquire a lock
  556. // when calling this method.
  557. StreamResult WriteOffsetLocked(const void* buffer, size_t bytes,
  558. size_t offset, size_t* bytes_written);
  559. StreamState state_; // keeps the opened/closed state of the stream
  560. scoped_array<char> buffer_; // the allocated buffer
  561. size_t buffer_length_; // size of the allocated buffer
  562. size_t data_length_; // amount of readable data in the buffer
  563. size_t read_position_; // offset to the readable data
  564. Thread* owner_; // stream callbacks are dispatched on this thread
  565. mutable CriticalSection crit_; // object lock
  566. DISALLOW_EVIL_CONSTRUCTORS(FifoBuffer);
  567. };
  568. ///////////////////////////////////////////////////////////////////////////////
  569. class LoggingAdapter : public StreamAdapterInterface {
  570. public:
  571. LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
  572. const std::string& label, bool hex_mode = false);
  573. void set_label(const std::string& label);
  574. virtual StreamResult Read(void* buffer, size_t buffer_len,
  575. size_t* read, int* error);
  576. virtual StreamResult Write(const void* data, size_t data_len,
  577. size_t* written, int* error);
  578. virtual void Close();
  579. protected:
  580. virtual void OnEvent(StreamInterface* stream, int events, int err);
  581. private:
  582. LoggingSeverity level_;
  583. std::string label_;
  584. bool hex_mode_;
  585. LogMultilineState lms_;
  586. DISALLOW_EVIL_CONSTRUCTORS(LoggingAdapter);
  587. };
  588. ///////////////////////////////////////////////////////////////////////////////
  589. // StringStream - Reads/Writes to an external std::string
  590. ///////////////////////////////////////////////////////////////////////////////
  591. class StringStream : public StreamInterface {
  592. public:
  593. explicit StringStream(std::string& str);
  594. explicit StringStream(const std::string& str);
  595. virtual StreamState GetState() const;
  596. virtual StreamResult Read(void* buffer, size_t buffer_len,
  597. size_t* read, int* error);
  598. virtual StreamResult Write(const void* data, size_t data_len,
  599. size_t* written, int* error);
  600. virtual void Close();
  601. virtual bool SetPosition(size_t position);
  602. virtual bool GetPosition(size_t* position) const;
  603. virtual bool GetSize(size_t* size) const;
  604. virtual bool GetAvailable(size_t* size) const;
  605. virtual bool ReserveSize(size_t size);
  606. private:
  607. std::string& str_;
  608. size_t read_pos_;
  609. bool read_only_;
  610. };
  611. ///////////////////////////////////////////////////////////////////////////////
  612. // StreamReference - A reference counting stream adapter
  613. ///////////////////////////////////////////////////////////////////////////////
  614. // Keep in mind that the streams and adapters defined in this file are
  615. // not thread-safe, so this has limited uses.
  616. // A StreamRefCount holds the reference count and a pointer to the
  617. // wrapped stream. It deletes the wrapped stream when there are no
  618. // more references. We can then have multiple StreamReference
  619. // instances pointing to one StreamRefCount, all wrapping the same
  620. // stream.
  621. class StreamReference : public StreamAdapterInterface {
  622. class StreamRefCount;
  623. public:
  624. // Constructor for the first reference to a stream
  625. // Note: get more references through NewReference(). Use this
  626. // constructor only once on a given stream.
  627. explicit StreamReference(StreamInterface* stream);
  628. StreamInterface* GetStream() { return stream(); }
  629. StreamInterface* NewReference();
  630. virtual ~StreamReference();
  631. private:
  632. class StreamRefCount {
  633. public:
  634. explicit StreamRefCount(StreamInterface* stream)
  635. : stream_(stream), ref_count_(1) {
  636. }
  637. void AddReference() {
  638. CritScope lock(&cs_);
  639. ++ref_count_;
  640. }
  641. void Release() {
  642. int ref_count;
  643. { // Atomic ops would have been a better fit here.
  644. CritScope lock(&cs_);
  645. ref_count = --ref_count_;
  646. }
  647. if (ref_count == 0) {
  648. delete stream_;
  649. delete this;
  650. }
  651. }
  652. private:
  653. StreamInterface* stream_;
  654. int ref_count_;
  655. CriticalSection cs_;
  656. DISALLOW_EVIL_CONSTRUCTORS(StreamRefCount);
  657. };
  658. // Constructor for adding references
  659. explicit StreamReference(StreamRefCount* stream_ref_count,
  660. StreamInterface* stream);
  661. StreamRefCount* stream_ref_count_;
  662. DISALLOW_EVIL_CONSTRUCTORS(StreamReference);
  663. };
  664. ///////////////////////////////////////////////////////////////////////////////
  665. // Flow attempts to move bytes from source to sink via buffer of size
  666. // buffer_len. The function returns SR_SUCCESS when source reaches
  667. // end-of-stream (returns SR_EOS), and all the data has been written successful
  668. // to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
  669. // returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
  670. // with the unexpected StreamResult value.
  671. // data_len is the length of the valid data in buffer. in case of error
  672. // this is the data that read from source but can't move to destination.
  673. // as a pass in parameter, it indicates data in buffer that should move to sink
  674. StreamResult Flow(StreamInterface* source,
  675. char* buffer, size_t buffer_len,
  676. StreamInterface* sink, size_t* data_len = NULL);
  677. ///////////////////////////////////////////////////////////////////////////////
  678. } // namespace talk_base
  679. #endif // TALK_BASE_STREAM_H_