NCBI C++ ToolKit
ncbi_conn_stream.hpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 #ifndef CONNECT___NCBI_CONN_STREAM__HPP
2 #define CONNECT___NCBI_CONN_STREAM__HPP
3 
4 /* $Id: ncbi_conn_stream.hpp 101111 2023-10-31 16:05:57Z lavr $
5  * ===========================================================================
6  *
7  * PUBLIC DOMAIN NOTICE
8  * National Center for Biotechnology Information
9  *
10  * This software/database is a "United States Government Work" under the
11  * terms of the United States Copyright Act. It was written as part of
12  * the author's official duties as a United States Government employee and
13  * thus cannot be copyrighted. This software/database is freely available
14  * to the public for use. The National Library of Medicine and the U.S.
15  * Government have not placed any restriction on its use or reproduction.
16  *
17  * Although all reasonable efforts have been taken to ensure the accuracy
18  * and reliability of the software and data, the NLM and the U.S.
19  * Government do not and cannot warrant the performance or results that
20  * may be obtained by using this software or data. The NLM and the U.S.
21  * Government disclaim all warranties, express or implied, including
22  * warranties of performance, merchantability or fitness for any particular
23  * purpose.
24  *
25  * Please cite the author in any work or product based on this material.
26  *
27  * ===========================================================================
28  *
29  * Authors: Denis Vakatov, Anton Lavrentiev
30  *
31  * File Description:
32  * @file ncbi_conn_stream.hpp
33  * CONN-based C++ streams
34  *
35  * Classes:
36  * CConn_IOStream
37  * Base class derived from "std::iostream" to perform I/O by means of the
38  * underlying CConn_Streambuf, which is implemented privately in
39  * ncbi_conn_streambuf.[ch]pp
40  *
41  * CConn_SocketStream
42  * I/O stream based on a socket connector.
43  *
44  * CConn_HttpStream
45  * I/O stream based on an HTTP connector (that is, a stream that can
46  * connect to an HTTP server and exchange information using the HTTP(S)
47  * protocol).
48  *
49  * CConn_ServiceStream
50  * I/O stream based on a service connector, which is able to exchange data
51  * to/from a named service that can be found via dispatcher/load-balancing
52  * daemon, and implemented as either HTTP GCI, standalone server, or NCBID
53  * service.
54  *
55  * CConn_MemoryStream
56  * In-memory stream of data (analogous to std::str[ing]stream).
57  *
58  * CConn_PipeStream
59  * I/O stream based on a PIPE connector, which is able to exchange data
60  * with a spawned child process, specified via a command.
61  *
62  * CConn_NamedPipeStream
63  * I/O stream based on a NAMEDPIPE connector, which is able to exchange
64  * data with another process (or self) via a pipe.
65  *
66  * CConn_FtpStream
67  * I/O stream based on an FTP connector, which is able to retrieve files
68  * and file lists from remote FTP servers, as well as to upload files.
69  *
70  * CConn_FTPDownloadStream
71  * Specialization of CConn_FtpStream for a (single) file download from an
72  * FTP server.
73  *
74  * CConn_FTPUploadStream
75  * Specialization of CConn_FtpStream for a (single) file upload to an FTP
76  * server
77  *
78  * API:
79  * NcbiOpenURL()
80  * Given a URL, return CConn_IOStream that is reading from the source.
81  * Supported schemes include: file://, http[s]://, ftp://, and finally, a
82  * named NCBI service (the null scheme).
83  *
84  */
85 
92 #include <connect/ncbi_socket.hpp>
93 #include <util/icanceled.hpp>
94 #include <utility>
95 
96 
97 /** @addtogroup ConnStreams
98  *
99  * @{
100  */
101 
102 
104 
105 
106 class CConn_Streambuf; // Forward declaration
107 
108 
109 const size_t kConn_DefaultBufSize = 16384; ///< I/O buffer size per direction
110 
111 
112 
113 /////////////////////////////////////////////////////////////////////////////
114 ///
115 /// Base class, inherited from "std::iostream", does both input and output,
116 /// using the specified CONNECTOR.
117 ///
118 /// The "buf_size" parameter designates the size of the internal I/O buffers,
119 /// which reside in between the stream and an underlying connector (which in
120 /// turn may do further buffering, if needed).
121 ///
122 /// By default, all input operations are tied to the output ones, which means
123 /// that any input attempt first flushes any pending output from the internal
124 /// buffers. The fConn_Untie flag can be used to untie the I/O directions.
125 ///
126 /// @note
127 /// CConn_IOStream implementation utilizes some connection callbacks on the
128 /// underlying CONN object. Care must be taken when intercepting the
129 /// callbacks using the native CONN API.
130 /// @sa
131 /// CONN_SetCallback
132 
134  virtual protected CConnIniter
135 {
136 public:
137  /// Polling timeout with the 0.0 time in it
138  static const STimeout kZeroTimeout;
139 
140  /// The values below must be compatible with TCONN_Flags
141  enum {
142  fConn_Untie = fCONN_Untie,///< do not flush before reading
143  fConn_DelayOpen = 2, ///< do not force CONN open in ctor
144  fConn_ReadUnbuffered = 4, ///< read buffer NOT to be alloc'd
145  fConn_WriteUnbuffered = 8 ///< write buffer NOT 2.b. alloc'd
146  } EConn_Flag;
147  typedef unsigned int TConn_Flags; ///< bitwise OR of EConn_Flag
148 
149  /// Create a stream based on CONN, which is to be closed upon stream dtor
150  /// but only if "close" parameter is passed as "true".
151  ///
152  /// @param conn
153  /// A C object of type CONN (ncbi_connection.h) on top of which the
154  /// stream is being constructed. May not be NULL.
155  /// @param close
156  /// True if to close CONN automatically (otherwise CONN remains open)
157  /// @param timeout
158  /// Default I/O timeout (including to open the stream)
159  /// @param buf_size
160  /// Default size of underlying stream buffer's I/O arena (per direction)
161  /// @param flags
162  /// Specifies whether to tie input and output (a tied stream flushes all
163  /// pending output prior to doing any input) and what to buffer
164  /// @param ptr
165  /// Specifies data which will be read from the stream prior to extracting
166  /// from the actual connection
167  /// @param size
168  /// The size of the area pointed to by the "ptr" argument
169  /// @sa
170  /// CONN, ncbi_connection.h
171  ///
173  (CONN conn,
174  bool close = false,
175  const STimeout* timeout = kDefaultTimeout,
176  size_t buf_size = kConn_DefaultBufSize,
177  TConn_Flags flags = 0,
178  CT_CHAR_TYPE* ptr = 0,
179  size_t size = 0);
180 
181  typedef pair<CONNECTOR, EIO_Status> TConnPair;
182  /// Helper class to build streams on top of CONNECTOR (internal use only).
183  class TConnector : public TConnPair
184  {
185  public:
186  /// @param connector
187  /// A C object of type CONNECTOR (ncbi_connector.h) on top of which a
188  /// stream will be constructed. NULL CONNECTOR indicates an error
189  /// (if none is passed in the second argument, eIO_Unknown results).
190  /// @param status
191  /// I/O status to use in the underlying streambuf (e.g. when
192  /// CONNECTOR is NULL), and if non-eIO_Success will also cause a
193  /// non-NULL CONNECTOR (if any passed in the first argument) to be
194  /// destroyed.
195  /// @sa
196  /// CONNECTOR, ncbi_connector.h
198  : TConnPair(connector, status != eIO_Success ? status :
199  connector ? eIO_Success : eIO_Unknown)
200  { }
201  };
202 protected:
203  /// Create a stream based on CONNECTOR -- only for internal use in derived
204  /// classes. The passed CONNECTOR always gets closed by stream dtor.
205  ///
206  /// @param connector
207  /// CONNECTOR coupled with an error code (if any)
208  /// @param timeout
209  /// Default I/O timeout (including to open the stream)
210  /// @param buf_size
211  /// Default size of underlying stream buffer's I/O arena (per direction)
212  /// @param flags
213  /// Specifies whether to tie input and output (a tied stream flushes all
214  /// pending output prior to doing any input), and what to buffer
215  /// @param ptr
216  /// Specifies data, which will be read from the stream prior to
217  /// extracting from the actual connection
218  /// @param size
219  /// The size of the area pointed to by the "ptr" argument
221  (const TConnector& connector,
222  const STimeout* timeout = kDefaultTimeout,
223  size_t buf_size = kConn_DefaultBufSize,
224  TConn_Flags flags = 0,
225  CT_CHAR_TYPE* ptr = 0,
226  size_t size = 0);
227 
228 public:
229  virtual ~CConn_IOStream();
230 
231  /// @return
232  /// Verbal connection type (empty if unknown)
233  /// @sa
234  /// CONN_GetType
235  string GetType(void) const;
236 
237  /// @return
238  /// Verbal connection description (empty if unknown)
239  /// @sa
240  /// CONN_Description
241  string GetDescription(void) const;
242 
243  /// Set connection timeout for "direction"
244  /// @param
245  /// Can accept a pointer to a finite timeout, or either of the special
246  /// values: kInfiniteTimeout, kDefaultTimeout
247  /// @return
248  /// eIO_Success if succeeded; other error code if failed
249  /// @sa
250  /// CONN_SetTimeout, SetReadTimeout, SetWriteTimeout
251  EIO_Status SetTimeout(EIO_Event direction,
252  const STimeout* timeout) const;
253 
254  /// @return
255  /// Connection timeout for "direction"
256  /// @return
257  /// eIO_Success if succeeded; other error code if failed
258  /// @sa
259  /// CONN_GetTimeout
260  const STimeout* GetTimeout(EIO_Event direction) const;
261 
262  /// @return
263  /// Status of the last I/O performed by the underlying CONN in the
264  /// specified "direction" (either eIO_Open, IO_Read, or eIO_Write);
265  /// if "direction" is not specified (eIO_Close), return status of the
266  /// last CONN I/O performed by the stream -- the intended use for the
267  /// latter is to obtain more detailed information in cases what a stream
268  /// operation or I/O has just failed.
269  /// @warning
270  /// This method is not a status of iostream! Neither this is the last
271  /// EIO_Status value returned by the other stream methods.
272  /// @sa
273  /// CONN_Status
274  EIO_Status Status(EIO_Event direction = eIO_Close) const;
275 
276  /// Flush the stream and fetch the response (w/o extracting any user data)
277  /// @return
278  /// eIO_Success if the operation was successful, and some input
279  /// (including none in case of EOF) will be available upon read
280  EIO_Status Fetch(const STimeout* timeout = kDefaultTimeout);
281 
282  /// Push the specified data "data" of size "size" back into the underlying
283  /// connection CONN (making it look like received yet unread data).
284  /// If there is any non-empty pending input sequence (internal read buffer)
285  /// it will be attempted to return to CONN first. Note that it can include
286  /// any initial read area ("ptr"), which could have been specified in the
287  /// ctor yet still unread, so potentially unwanted data copying may result.
288  /// @return
289  /// Any status other than eIO_Success means that nothing from "data" has
290  /// been returned to the connection
291  /// @note
292  /// Can be used to push just the pending internal input alone back into
293  /// CONN if used with a "size" of 0 ("data" is ignored then).
294  /// @sa
295  /// CONN_Pushback
296  virtual EIO_Status Pushback(const CT_CHAR_TYPE* data, streamsize size)
297  { return x_Pushback(data, size); }
298 
299  /// Get underlying SOCK, if available (e.g. after Fetch())
300  SOCK GetSOCK(void);
301 
302  /// Get CSocket, if available (else empty). The returned CSocket doesn't
303  /// own the underlying SOCK, and is valid for as long as the stream exists.
304  /// @sa
305  /// CSocket, SOCK
306  CSocket& GetSocket(void);
307 
308  /// Close CONNection, free all internal buffers and underlying structures,
309  /// and render the stream unusable for further I/O
310  /// @return
311  /// eIO_Success when closed without errors; eIO_Closed if it was already
312  /// closed; other error code if failed to close in an orderly fashion
313  /// @warning
314  /// Regardless of the return code, this method makes the stream unable to
315  /// accept any further actions and / or I/O (they all would fail).
316  /// @note
317  /// Can be used at places where reaching end-of-scope for the stream.
318  /// would be impractical
319  /// @sa
320  /// CONN_Close
321  virtual EIO_Status Close(void);
322 
323  /// Cancellation support
324  /// @note
325  /// The ICanceled implementation must be derived from CObject as its
326  /// first superclass.
327  /// @sa
328  /// ICanceled
329  EIO_Status SetCanceledCallback(const ICanceled* canceled);
330 
331  /// @return
332  /// Internal CONNection handle, which is still owned and used by the
333  /// stream (or NULL if no such handle exists)
334  /// @note
335  /// Connection can have additional flags set for I/O processing
336  /// @sa
337  /// CONN, ncbi_connection.h, CONN_GetFlags
338  CONN GetCONN(void) const;
339 
340  /// Equivalent to CONN_Wait(GetCONN(), event, timeout)
341  /// @param event
342  /// eIO_Read or eIO_Write
343  /// @param timeout
344  /// Time to wait for the event (poll if zero time specified, and return
345  /// immediately)
346  /// @return
347  /// eIO_Success if the event is available; eIO_Timeout if the time has
348  /// expired; other code to signify some error condition
349  /// @sa
350  /// CONN_Wait
351  EIO_Status Wait(EIO_Event event,
352  const STimeout* timeout = &kZeroTimeout);
353 
354 protected:
355  EIO_Status x_Pushback(const CT_CHAR_TYPE* data, streamsize size,
356  bool push = false);
357  void x_Destroy(void);
358 
359 protected:
360  // Stream buffer
362 
363 private:
364  // Resource storage
365  unique_ptr<CConn_Streambuf> x_CSb;
367 
368  // Cancellation
369  SCONN_Callback m_CB[4];
371  static EIO_Status sx_IsCanceled(CONN conn,TCONN_Callback type,void* data);
372 
373 private:
374  // Disable copy constructor and assignment
376  CConn_IOStream& operator= (const CConn_IOStream&);
377 };
378 
379 
381 public:
382  const STimeout* GetTimeout(void) const { return m_Timeout; }
383 
384 protected:
386  : m_Timeout(timeout)
387  { }
388 
389 private:
391 };
392 
393 
395 {
396 public:
398 
399 protected:
401  : CConn_IOStreamSetTimeout(timeout)
402  { }
404 };
405 
406 
408 {
409  return CConn_IOStreamSetReadTimeout(timeout);
410 }
411 
412 
413 /// Stream manipulator "is >> SetReadTimeout(timeout)"
416 {
417  if (is.good() && is.SetTimeout(eIO_Read, s.GetTimeout()) != eIO_Success)
418  is.clear(NcbiBadbit);
419  return is;
420 }
421 
422 
424 {
425 public:
427 
428 protected:
430  : CConn_IOStreamSetTimeout(timeout)
431  { }
433 };
434 
435 
437 {
438  return CConn_IOStreamSetWriteTimeout(timeout);
439 }
440 
441 
442 /// Stream manipulator "os << SetWriteTimeout(timeout)"
445 {
446  if (os.good() && os.SetTimeout(eIO_Write, s.GetTimeout()) != eIO_Success)
447  os.clear(NcbiBadbit);
448  return os;
449 }
450 
451 
453 {
455  return m_Socket;
456 }
457 
458 
459 
460 /////////////////////////////////////////////////////////////////////////////
461 ///
462 /// This stream exchanges data in a TCP channel, using the SOCK socket API.
463 /// The endpoint is specified as a "host:port" pair. The maximal number of
464 /// connection attempts is given via "max_try".
465 /// More details on that: <connect/ncbi_socket_connector.h>.
466 ///
467 /// @sa
468 /// SOCK_CreateConnector, SOCK_Create
469 ///
470 
472 {
473 public:
474  /// Create a direct connection with host:port.
475  ///
476  /// @param host
477  /// Host to connect to
478  /// @param port
479  /// ... and port number
480  /// @param max_try
481  /// Number of attempts
482  /// @param timeout
483  /// Default I/O timeout
484  /// @param buf_size
485  /// Default buffer size
486  /// @param flags
487  /// Specifies whether to tie input and output (a tied stream flushes all
488  /// pending output prior to doing any input), and what to buffer
489  /// @sa
490  /// CConn_IOStream
492  (const string& host, ///< host to connect to
493  unsigned short port, ///< ... and port number
494  unsigned short max_try, ///< number of attempts
495  const STimeout* timeout = kDefaultTimeout,
496  size_t buf_size = kConn_DefaultBufSize,
497  TConn_Flags flags = 0);
498 
499  /// Create a direct connection with "host:port" and send an initial "data"
500  /// block of the specified "size" first; the remaining communication can
501  /// proceed as usual.
502  ///
503  /// @param host
504  /// Host to connect to
505  /// @param port
506  /// ... and port number (however, see a note below)
507  /// @param data
508  /// Pointer to block of data to send once connection is ready
509  /// @param size
510  /// Size of the data block to send (or 0 if to send nothing)
511  /// @param flgs
512  /// Socket flgs (see <connect/ncbi_socket.h>)
513  /// @param max_try
514  /// Number of attempts
515  /// @param timeout
516  /// Default I/O timeout
517  /// @param buf_size
518  /// Default buffer size
519  /// @param flags
520  /// Specifies whether to tie input and output (a tied stream flushes all
521  /// pending output prior to doing any input), and what to buffer
522  /// @note As a special case, if "port" is specified as 0, then the "host"
523  /// parameter is expected to have a "host:port" string as its value.
524  /// @sa
525  /// CConn_IOStream
527  (const string& host, ///< host[:port] to connect
528  unsigned short port = 0, ///< ... and port number
529  const void* data = 0, ///< initial data block
530  size_t size = 0, ///< size of the data block
531  TSOCK_Flags flgs = fSOCK_LogDefault, ///< see ncbi_socket.h
532  unsigned short max_try = DEF_CONN_MAX_TRY, ///< number of attempts
533  const STimeout* timeout = kDefaultTimeout,
534  size_t buf_size = kConn_DefaultBufSize,
535  TConn_Flags flags = 0);
536 
537  /// This variant uses an existing socket "sock" to build a stream upon it.
538  /// The caller may retain the ownership of "sock" by passing "if_to_own" as
539  /// "eNoOwnership" to the stream constructor -- in that case, the socket
540  /// "sock" will not be closed / destroyed upon stream destruction, and can
541  /// further be used (including proper closing when no longer needed).
542  /// Otherwise, "sock" becomes invalid once the stream is closed/destroyed.
543  /// NOTE: To maintain data integrity and consistency, "sock" should not
544  /// be used elsewhere while it is also being in use by the stream.
545  /// More details: <ncbi_socket_connector.h>::SOCK_CreateConnectorOnTop().
546  ///
547  /// @param sock
548  /// Socket to build the stream on
549  /// @param if_to_own
550  /// Whether the sock object is owned (managed) by the stream at dtor
551  /// @param timeout
552  /// Default I/O timeout
553  /// @param buf_size
554  /// Default buffer size
555  /// @param flags
556  /// Specifies whether to tie input and output (a tied stream flushes all
557  /// pending output prior to doing any input), and what to buffer
558  /// @sa
559  /// CConn_IOStream, ncbi_socket.h, SOCK_CreateConnectorOnTop
561  (SOCK sock, ///< socket
562  EOwnership if_to_own, ///< whether stream to own "sock" param
563  const STimeout* timeout = kDefaultTimeout,
564  size_t buf_size = kConn_DefaultBufSize,
565  TConn_Flags flags = 0);
566 
567  /// This variant uses an existing CSocket to build a stream up on it.
568  /// NOTE: this always revokes all ownership of the "socket"'s internals
569  /// (effectively leaving the CSocket empty); CIO_Exception(eInvalidArg)
570  /// is thrown if the internal SOCK is not owned by the passed CSocket.
571  /// More details: <ncbi_socket_connector.h>::SOCK_CreateConnectorOnTop().
572  ///
573  /// @param socket
574  /// Socket to build the stream up on
575  /// @param timeout
576  /// Default I/O timeout
577  /// @param buf_size
578  /// Default buffer size
579  /// @param flags
580  /// Specifies whether to tie input and output (a tied stream flushes all
581  /// pending output prior to doing any input), and what to buffer
582  /// @sa
583  /// CConn_IOStream, ncbi_socket.hpp, SOCK_CreateConnectorOnTop
585  (CSocket& socket, ///< socket, underlying SOCK always grabbed
586  const STimeout* timeout = kDefaultTimeout,
587  size_t buf_size = kConn_DefaultBufSize,
588  TConn_Flags flags = 0);
589 
590  /// Create a tunneled socket stream connection.
591  ///
592  /// The following fields of SConnNetInfo are used (other ignored):
593  ///
594  /// scheme -- must be http or unspecified, checked
595  /// host:port -- target server
596  /// http_proxy_host:http_proxy_port -- HTTP proxy server to tunnel thru
597  /// http_proxy_user:http_proxy_pass -- credentials for the proxy, if needed
598  /// http_proxy_leak -- ignore bad proxy and connect direct
599  /// timeout -- timeout to connect to HTTP proxy
600  /// firewall -- if true then look at proxy_server
601  /// proxy_server -- use as "host" if non-empty and FW
602  /// debug_printout -- how to log socket data by default
603  /// http_push_auth -- whether to push credentials at once
604  ///
605  /// @param net_info
606  /// Connection point and proxy tunnel location
607  /// @param data
608  /// Pointer to block of data to send once connection is ready
609  /// @param size
610  /// Size of the data block to send (or 0 if to send nothing)
611  /// @param flgs
612  /// Socket flags (see <connect/ncbi_socket.h>)
613  /// @param timeout
614  /// Default I/O timeout
615  /// @param buf_size
616  /// Default buffer size
617  /// @param flags
618  /// Specifies whether to tie input and output (a tied stream flushes all
619  /// pending output prior to doing any input), and what to buffer
620  /// @sa
621  /// CConn_IOStream, SConnNetInfo
623  (const SConnNetInfo& net_info,
624  const void* data = 0,
625  size_t size = 0,
627  const STimeout* timeout = kDefaultTimeout,
628  size_t buf_size = kConn_DefaultBufSize,
629  TConn_Flags flags = 0);
630 };
631 
632 
633 
634 /// Helper class to fetch HTTP status code and text
636  int m_Code;
638  string m_Header;
639 
641  : m_Code(0)
642  { }
643 
644  EHTTP_HeaderParse Parse(const char* header);
645 
646  void Clear(void)
647  { m_Code = 0; m_Text.clear(); m_Header.clear(); }
648 
649 private:
650  // Disable copy constructor and assignment
653 };
654 
655 
656 /// Helper base class for HTTP-like streams
658 {
659 public:
660  /// Get the last seen HTTP status code, if available
661  int GetStatusCode(void) const {return m_StatusData.m_Code; }
662 
663  /// Get the last seen HTTP status text, if available
664  const CTempString GetStatusText(void) const {return m_StatusData.m_Text; }
665 
666  /// Get the last seen HTTP header text, if available
667  const string& GetHTTPHeader(void) const {return m_StatusData.m_Header;}
668 
669 protected:
670  /// @sa
671  /// CConn_IOStream
673  (const TConnector& connector,
674  const STimeout* timeout,
675  size_t buf_size,
676  TConn_Flags flags = 0)
677  : CConn_IOStream(connector, timeout, buf_size, flags)
678  { }
679 
680 protected:
681  // HTTP status code & text seen last
683 };
684 
685 
686 /////////////////////////////////////////////////////////////////////////////
687 ///
688 /// This stream exchanges data with an HTTP server located at the URL:
689 /// http[s]://host[:port]/path[?args]
690 ///
691 /// Note that "path" must include the leading slash, "args" can be empty, in
692 /// which case the '?' does not get appended to the path.
693 ///
694 /// "User_header" (if not empty) should be a sequence of lines in the form
695 /// 'HTTP-tag: Tag value', with each line separated by a CR LF sequence, and
696 /// the last line optionally terminated with a CR LF sequence. For example:
697 /// "Content-Encoding: gzip\r\nContent-Type: application/octet-stream"
698 /// It is included in the HTTP-header of each transaction.
699 ///
700 /// More elaborate specification(s) of the server can be made via the
701 /// SConnNetInfo structure, which otherwise will be created with the use of a
702 /// standard registry section to obtain default values from (details:
703 /// <connect/ncbi_connutil.h>). To make sure the actual user header is empty,
704 /// remember to reset it with ConnNetInfo_SetUserHeader(net_info, 0).
705 ///
706 /// THTTP_Flags and other details: <connect/ncbi_http_connector.h>.
707 ///
708 /// Provided "timeout" is set at the connection level, and if different from
709 /// kDefaultTimeout, it overrides a value supplied by the HTTP connector (the
710 /// latter value is kept at SConnNetInfo::timeout).
711 ///
712 /// @sa
713 /// CConn_IOStream, HTTP_CreateConnector, ConnNetInfo_Create
714 ///
715 
717 {
718 public:
720  (const string& host,
721  const string& path,
722  const string& args = kEmptyStr,
723  const string& user_header = kEmptyStr,
724  unsigned short port = 0, ///< default(e.g. 80=HTTP/443=HTTPS)
726  const STimeout* timeout = kDefaultTimeout,
727  size_t buf_size = kConn_DefaultBufSize
728  );
729 
731  (const string& url,
733  const STimeout* timeout = kDefaultTimeout,
734  size_t buf_size = kConn_DefaultBufSize
735  );
736 
738  (const string& url,
739  EReqMethod method,
740  const string& user_header = kEmptyStr,
742  const STimeout* timeout = kDefaultTimeout,
743  size_t buf_size = kConn_DefaultBufSize
744  );
745 
747  (const string& url,
748  const SConnNetInfo* net_info,
749  const string& user_header = kEmptyStr,
750  FHTTP_ParseHeader parse_header = 0,
751  void* user_data = 0,
752  FHTTP_Adjust adjust = 0,
755  const STimeout* timeout = kDefaultTimeout,
756  size_t buf_size = kConn_DefaultBufSize
757  );
758 
760  (const SConnNetInfo* net_info = 0,
761  const string& user_header = kEmptyStr,
762  FHTTP_ParseHeader parse_header = 0,
763  void* user_data = 0,
764  FHTTP_Adjust adjust = 0,
767  const STimeout* timeout = kDefaultTimeout,
768  size_t buf_size = kConn_DefaultBufSize
769  );
770 
771  virtual ~CConn_HttpStream();
772 
773  /// Set new URL to hit next
774  void SetURL(const string& url) { m_URL = url; }
775 
776 protected:
777  // Chained callbacks and data
778  void* m_UserData;
782 
783  // URL to hit next
784  string m_URL;
785 
786 private:
787  // Callback interceptors
788  static int/*bool*/ sx_Adjust (SConnNetInfo* net_info,
789  void* data,
790  unsigned int count);
791  static void sx_Cleanup (void* data);
792  static EHTTP_HeaderParse sx_ParseHeader(const char* header,
793  void* data,
794  int code);
795 };
796 
797 
798 
799 /////////////////////////////////////////////////////////////////////////////
800 ///
801 /// This stream exchanges data with a named service, in a constraint that the
802 /// service is implemented as one of the specified server "types"
803 /// (details: <connect/ncbi_server_info.h>).
804 ///
805 /// Additional specifications can be passed in an SConnNetInfo structure,
806 /// otherwise created by using the service name as a registry section to obtain
807 /// the information from (details: <connect/ncbi_connutil.h>).
808 ///
809 /// In case when the service is implemented over underlying HTTP (which is NOT
810 /// generally guaranteed), the HTTP status data become available.
811 ///
812 /// Provided "timeout" is set at the connection level, and if different from
813 /// kDefaultTimeout, it overrides the value supplied by an underlying connector
814 /// (the latter value is kept in SConnNetInfo::timeout).
815 ///
816 /// @sa
817 /// SERVICE_CreateConnector
818 ///
819 
821 {
822 public:
824  (const string& service,
826  const SConnNetInfo* net_info = 0,
827  const SSERVICE_Extra* extra = 0,
828  const STimeout* timeout = kDefaultTimeout,
829  size_t buf_size = kConn_DefaultBufSize);
830 
832  (const string& service,
833  const string& user_header,
835  const SSERVICE_Extra* extra = 0,
836  const STimeout* timeout = kDefaultTimeout,
837  size_t buf_size = kConn_DefaultBufSize);
838 
839  virtual ~CConn_ServiceStream();
840 
841 protected:
842  // Chained callbacks and data
844 
845 private:
846  // Callback interceptors
847  static void sx_Reset (void* data);
848  static int/*bool*/ sx_Adjust (SConnNetInfo* net_info,
849  void* data,
850  unsigned int count);
851  static void sx_Cleanup (void* data);
852  static EHTTP_HeaderParse sx_ParseHeader(const char* header,
853  void* data,
854  int code);
855  static const SSERV_Info* sx_GetNextInfo(void* data,
856  SERV_ITER iter);
857 };
858 
859 
860 
861 /////////////////////////////////////////////////////////////////////////////
862 ///
863 /// In-memory stream (a la strstream or stringstream)
864 ///
865 /// @sa
866 /// MEMORY_CreateConnector
867 ///
868 
870 {
871 public:
872  CConn_MemoryStream(size_t buf_size = kConn_DefaultBufSize);
873 
874  /// Build a stream on top of an NCBI buffer (which in turn
875  /// could have been built over a memory area of a specified size).
876  /// BUF's ownership is assumed by the stream as specified in "owner".
878  EOwnership owner = eTakeOwnership,
879  size_t buf_size = kConn_DefaultBufSize);
880 
881  /// Build a stream on top of an existing data area of a specified size.
882  /// The contents of the area are what will be read first from the stream.
883  /// Writing to the stream will _not_ modify the contents of the area.
884  /// When read from the stream, the written data will appear following the
885  /// initial data block.
886  /// Ownership of the area pointed to by "ptr" is controlled by the "owner"
887  /// parameter, and if the ownership is passed to the stream the area will
888  /// be deleted by "delete[] (char*)" from the stream destructor. That is,
889  /// if there are any requirements to be considered for deleting the area
890  /// (like deleting an object or an array of objects), then the ownership
891  /// must not be passed to the stream.
892  /// Note that the area pointed to by "ptr" should not be changed while it
893  /// is still holding the data yet to be read from the stream.
894  CConn_MemoryStream(const void* ptr,
895  size_t size,
896  EOwnership owner/**no default for safety*/,
897  size_t buf_size = kConn_DefaultBufSize);
898 
899  virtual ~CConn_MemoryStream();
900 
901  virtual EIO_Status Pushback(const CT_CHAR_TYPE* data, streamsize size)
902  { return x_Pushback(data, size, true); }
903 
904  /// The CConnMemoryStream::To* methods allow to obtain unread portion of
905  /// the stream into a single container (as a string or a vector) so that
906  /// all data is kept in sequential memory locations.
907  /// Note that the operation is considered an extraction, so it effectively
908  /// empties the stream.
909  void ToString(string*); ///< fill in the data, NULL is not accepted
910  void ToVector(vector<char>*);///< fill in the data, NULL is not accepted
911 
912  /// Get the underlying BUF handle (it still remains managed by the stream)
913  /// @note
914  /// Causes the stream to flush().
915  BUF GetBUF(void);
916 
917 protected:
918  const void* m_Ptr; ///< pointer to read memory area (if owned)
919 };
920 
921 
922 
923 /////////////////////////////////////////////////////////////////////////////
924 ///
925 /// CConn_PipeStream for command piping
926 ///
927 /// @note
928 /// Exercise caution when operating on the underlying pipe while it's being
929 /// in use by the stream as that may cause some unpredictable behavior.
930 ///
931 /// Provided "timeout" is set at the connection level if different from
932 /// kDefaultTimeout (which is infinite for this class by default).
933 ///
934 /// @sa
935 /// PIPE_CreateConnector, CPipe::ECreateFlag, CPipe
936 ///
937 
939 {
940 public:
942  (const string& cmd,
943  const vector<string>& args,
945  size_t pipe_size = 0,
946  const STimeout* timeout = kDefaultTimeout,
947  size_t buf_size = kConn_DefaultBufSize
948  );
949  virtual ~CConn_PipeStream();
950 
951  virtual EIO_Status Close(void);
952 
953  /// A valid exit code is only made available after an explicit Close()
954  /// @sa
955  /// CProcess::CExitInfo
956  int GetExitCode(void) const { return m_ExitCode; }
957 
958  /// Return an underlying CPipe; it's valid for as long as the stream exists
959  /// @sa
960  /// CPipe
961  CPipe& GetPipe(void) { return *m_Pipe; }
962 
963 protected:
964  CPipe* m_Pipe; ///< Underlying pipe.
965  int m_ExitCode; ///< Process exit code.
966 };
967 
968 
969 
970 /////////////////////////////////////////////////////////////////////////////
971 ///
972 /// CConn_NamedPipeStream for inter-process communication
973 ///
974 /// Provided "timeout" is set at the connection level if different from
975 /// kDefaultTimeout (which is infinite for this class by default).
976 ///
977 /// @sa
978 /// NAMEDPIPE_CreateConnector, CNamedPipe
979 ///
980 
982 {
983 public:
985  (const string& pipename,
986  size_t pipesize = 0/*default*/,
987  const STimeout* timeout = kDefaultTimeout,
988  size_t buf_size = kConn_DefaultBufSize
989  );
990 };
991 
992 
993 
994 /////////////////////////////////////////////////////////////////////////////
995 ///
996 /// CConn_FtpStream is an elaborate FTP client, can be used for data
997 /// downloading and/or uploading to and from an FTP server.
998 /// See <connect/ncbi_ftp_connector.h> for detailed explanations
999 /// of supported features.
1000 ///
1001 /// Provided "timeout" is set at the connection level, and if different from
1002 /// kDefaultTimeout, it overrides a value supplied by the FTP connector
1003 /// (the latter value is kept at SConnNetInfo::timeout).
1004 ///
1005 /// @sa
1006 /// FTP_CreateConnector
1007 ///
1008 
1010 {
1011 public:
1013  (const string& host,
1014  const string& user,
1015  const string& pass,
1016  const string& path = kEmptyStr,
1017  unsigned short port = 0,
1018  TFTP_Flags flag = 0,
1019  const SFTP_Callback* cmcb = 0,
1020  const STimeout* timeout = kDefaultTimeout,
1021  size_t buf_size = kConn_DefaultBufSize
1022  );
1023 
1025  (const SConnNetInfo& net_info,
1026  TFTP_Flags flag = 0,
1027  const SFTP_Callback* cmcb = 0,
1028  const STimeout* timeout = kDefaultTimeout,
1029  size_t buf_size = kConn_DefaultBufSize
1030  );
1031 
1032  virtual ~CConn_FtpStream();
1033 
1034  /// Abort any command in progress, read and discard all input data, and
1035  /// clear stream error state when successful (eIO_Success returns)
1036  /// @note
1037  /// The call empties out both the stream and the underlying CONN.
1038  virtual EIO_Status Drain(const STimeout* timeout = kDefaultTimeout);
1039 
1040 protected:
1041  // Chained callback and data
1043 
1044 private:
1045  // Callback interceptor
1046  static EIO_Status sx_FtpCallback(void* data,
1047  const char* cmd,
1048  const char* arg);
1049 };
1050 
1051 
1052 /// CConn_FtpStream specialization (ctor) for download
1053 ///
1054 /// @warning
1055 /// Pay attention to the order of parameters vs generic CConn_FtpStream ctor.
1056 ///
1058 {
1059 public:
1061  (const string& host,
1062  const string& file = kEmptyStr,
1063  const string& user = "ftp",
1064  const string& pass = "-none@", // "-" helps make login quieter
1065  const string& path = kEmptyStr,
1066  unsigned short port = 0, ///< 0 means default (21 for FTP)
1067  TFTP_Flags flag = 0,
1068  const SFTP_Callback* cmcb = 0,
1069  Uint8 offset = 0, ///< file offset to begin download at
1070  const STimeout* timeout = kDefaultTimeout,
1071  size_t buf_size = kConn_DefaultBufSize
1072  );
1073 
1075  (const SConnNetInfo& net_info,
1076  TFTP_Flags flag = 0,
1077  const SFTP_Callback* cmcb = 0,
1078  Uint8 offset = 0, ///< file offset to begin download at
1079  const STimeout* timeout = kDefaultTimeout,
1080  size_t buf_size = kConn_DefaultBufSize
1081  );
1082 
1083 protected:
1084  void x_InitDownload(const string& file, Uint8 offset);
1085 };
1086 
1087 
1088 /// CConn_FtpStream specialization (ctor) for upload
1089 ///
1091 {
1092 public:
1094  (const string& host,
1095  const string& user,
1096  const string& pass,
1097  const string& file = kEmptyStr,
1098  const string& path = kEmptyStr,
1099  unsigned short port = 0, ///< 0 means default (21 for FTP)
1100  TFTP_Flags flag = 0,
1101  Uint8 offset = 0, ///< file offset to start upload at
1102  const STimeout* timeout = kDefaultTimeout
1103  );
1104 
1106  (const SConnNetInfo& net_info,
1107  TFTP_Flags flag = 0,
1108  Uint8 offset = 0, ///< file offset to start upload at
1109  const STimeout* timeout = kDefaultTimeout
1110  );
1111 
1112 protected:
1113  void x_InitUpload(const string& file, Uint8 offset);
1114 };
1115 
1116 
1117 
1118 /////////////////////////////////////////////////////////////////////////////
1119 ///
1120 /// Given a URL, open the data source and make it available for _reading_.
1121 /// See <connect/ncbi_connutil.h> for supported schemes.
1122 ///
1123 /// If "url" looks like an identifier (no scheme provided), then it will be
1124 /// opened as a named NCBI service (using CConn_ServiceStream); if the "url"
1125 /// looks like a string in the form "host:port", a socket to that host and port
1126 /// will be connected (using CConn_SocketStream); otherwise, a stream will be
1127 /// created according to the URL scheme (recognized are: "ftp://", "http://",
1128 /// "https://", and "file://").
1129 ///
1130 /// @warning
1131 /// Writing to the resultant stream is undefined, unless it's either a
1132 /// service or a socket stream.
1133 ///
1134 extern NCBI_XCONNECT_EXPORT
1135 CConn_IOStream* NcbiOpenURL(const string& url,
1136  size_t buf_size = kConn_DefaultBufSize);
1137 
1138 
1140 
1141 
1142 /* @} */
1143 
1144 #endif /* CONNECT___NCBI_CONN_STREAM__HPP */
Helper hook-up class that installs default logging/registry/locking (but only if they have not yet be...
CConn_FtpStream specialization (ctor) for download.
CConn_FtpStream specialization (ctor) for upload.
CConn_FtpStream is an elaborate FTP client, can be used for data downloading and/or uploading to and ...
Helper base class for HTTP-like streams.
This stream exchanges data with an HTTP server located at the URL: http[s]://host[:port]/path[?...
const STimeout * GetTimeout(void) const
const STimeout * GetTimeout(void) const
Helper class to build streams on top of CONNECTOR (internal use only).
Base class, inherited from "std::iostream", does both input and output, using the specified CONNECTOR...
In-memory stream (a la strstream or stringstream)
CConn_NamedPipeStream for inter-process communication.
CConn_PipeStream for command piping.
This stream exchanges data with a named service, in a constraint that the service is implemented as o...
This stream exchanges data in a TCP channel, using the SOCK socket API.
CPipe –.
Definition: ncbi_pipe.hpp:76
CSocket::
CTempString implements a light-weight string on top of a storage buffer whose lifetime management is ...
Definition: tempstr.hpp:65
Interface for testing cancellation request in a long lasting operation.
Definition: icanceled.hpp:51
static CS_COMMAND * cmd
Definition: ct_dynamic.c:26
static void cleanup(void)
Definition: ct_dynamic.c:30
static CS_CONNECTION * conn
Definition: ct_dynamic.c:25
static uch flags
int close(int fd)
Definition: connection.cpp:45
@ eTakeOwnership
An object can take ownership of another.
Definition: ncbi_types.h:136
@ eNoOwnership
No ownership is assumed.
Definition: ncbi_types.h:135
int GetStatusCode(void) const
Get the last seen HTTP status code, if available.
CConn_IOStream & operator<<(CConn_IOStream &os, const CConn_IOStreamSetWriteTimeout &s)
Stream manipulator "os << SetWriteTimeout(timeout)".
SHTTP_StatusData m_StatusData
CConn_IOStreamSetReadTimeout(const STimeout *timeout)
SFTP_Callback m_Cmcb
CConn_IOStreamSetWriteTimeout SetWriteTimeout(const STimeout *timeout)
static const STimeout kZeroTimeout
Polling timeout with the 0.0 time in it.
const CTempString GetStatusText(void) const
Get the last seen HTTP status text, if available.
TConnector(CONNECTOR connector, EIO_Status status=eIO_Success)
CConn_Streambuf * m_CSb
SHTTP_StatusData(const SHTTP_StatusData &)
FHTTP_Adjust m_UserAdjust
const STimeout * GetTimeout(void) const
CConn_IOStream(const CConn_IOStream &)
virtual EIO_Status Pushback(const CT_CHAR_TYPE *data, streamsize size)
Push the specified data "data" of size "size" back into the underlying connection CONN (making it loo...
EIO_Status SetTimeout(EIO_Event direction, const STimeout *timeout) const
Set connection timeout for "direction".
pair< CONNECTOR, EIO_Status > TConnPair
friend CConn_IOStreamSetReadTimeout SetReadTimeout(const STimeout *)
CConn_IOStreamSetTimeout(const STimeout *timeout)
CConn_IOStream & operator>>(CConn_IOStream &is, const CConn_IOStreamSetReadTimeout &s)
Stream manipulator "is >> SetReadTimeout(timeout)".
friend CConn_IOStreamSetWriteTimeout SetWriteTimeout(const STimeout *)
const string & GetHTTPHeader(void) const
Get the last seen HTTP header text, if available.
SHTTP_StatusData & operator=(const SHTTP_StatusData &)
CConn_IOStreamSetReadTimeout SetReadTimeout(const STimeout *timeout)
SOCK GetSOCK(void)
Get underlying SOCK, if available (e.g. after Fetch())
int GetExitCode(void) const
A valid exit code is only made available after an explicit Close()
CConn_IOStream * NcbiOpenURL(const string &url, size_t buf_size=kConn_DefaultBufSize)
Given a URL, open the data source and make it available for _reading_.
const void * m_Ptr
pointer to read memory area (if owned)
FHTTP_Cleanup m_UserCleanup
CPipe & GetPipe(void)
Return an underlying CPipe; it's valid for as long as the stream exists.
CConn_HttpStream_Base(const TConnector &connector, const STimeout *timeout, size_t buf_size, TConn_Flags flags=0)
virtual EIO_Status Pushback(const CT_CHAR_TYPE *data, streamsize size)
Push the specified data "data" of size "size" back into the underlying connection CONN (making it loo...
EHTTP_HeaderParse Parse(const char *header)
FHTTP_ParseHeader m_UserParseHeader
CPipe * m_Pipe
Underlying pipe.
CSocket & GetSocket(void)
Get CSocket, if available (else empty).
unique_ptr< CConn_Streambuf > x_CSb
unsigned int TConn_Flags
bitwise OR of EConn_Flag
int m_ExitCode
Process exit code.
const size_t kConn_DefaultBufSize
I/O buffer size per direction.
CConn_IOStreamSetWriteTimeout(const STimeout *timeout)
CConstIRef< ICanceled > m_Canceled
void SetURL(const string &url)
Set new URL to hit next.
unsigned int THTTP_Flags
Bitwise OR of EHTTP_Flag.
int(* FHTTP_Adjust)(SConnNetInfo *net_info, void *user_data, unsigned int failure_count)
unsigned int TCONN_Callback
void(* FHTTP_Cleanup)(void *user_data)
EHTTP_HeaderParse
The extended version HTTP_CreateConnectorEx() is able to track the HTTP response chain and also chang...
EHTTP_HeaderParse(* FHTTP_ParseHeader)(const char *http_header, void *user_data, int server_error)
unsigned int TFTP_Flags
@ fHTTP_AutoReconnect
See HTTP_CreateConnectorEx()
@ fCONN_Untie
do not call flush method prior to reading
unsigned int TCreateFlags
bitwise OR of "ECreateFlag"
Definition: ncbi_pipe.hpp:111
uint64_t Uint8
8-byte (64-bit) unsigned integer
Definition: ncbitype.h:105
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
unsigned int TSERV_Type
Bitwise OR of ESERV_Type[Special].
Definition: ncbi_service.h:94
@ fSERV_Any
Definition: ncbi_service.h:79
void Reset(SOCK sock, EOwnership if_to_own, ECopyTimeout whence)
Close the current underlying "SOCK" (if any, and if owned), and from now on use "sock" as the underly...
unsigned int TSOCK_Flags
bitwise "OR" of ESOCK_Flags
Definition: ncbi_socket.h:503
@ eCopyTimeoutsFromSOCK
Definition: ncbi_socket.hpp:52
@ fSOCK_LogDefault
Definition: ncbi_socket.h:491
IO_PREFIX::iostream CNcbiIostream
Portable alias for iostream.
Definition: ncbistre.hpp:152
#define NcbiBadbit
Definition: ncbistre.hpp:571
#define CT_CHAR_TYPE
Definition: ncbistre.hpp:729
#define kEmptyStr
Definition: ncbistr.hpp:123
void clear(void)
Clears the string.
Definition: tempstr.hpp:351
EIO_Status
I/O status.
Definition: ncbi_core.h:132
EReqMethod
enum ENcbiOwnership EOwnership
Ownership relations between objects.
EIO_Event
I/O event (or direction).
Definition: ncbi_core.h:118
#define kDefaultTimeout
Definition: ncbi_types.h:81
#define DEF_CONN_MAX_TRY
@ eIO_Success
everything is fine, no error occurred
Definition: ncbi_core.h:133
@ eIO_Unknown
unknown I/O error (likely fatal but can retry)
Definition: ncbi_core.h:139
@ eIO_Write
write
Definition: ncbi_core.h:121
@ eIO_Close
also serves as an error indicator in SOCK_Poll
Definition: ncbi_core.h:123
@ eIO_Read
read
Definition: ncbi_core.h:120
#define NCBI_XCONNECT_EXPORT
FILE * file
char * buf
list< Ts... > push
const struct ncbi::grid::netcache::search::fields::SIZE size
static const STimeout kZeroTimeout
static int x_Pushback(SOCK sock, BUF buf)
Implement CONNECTOR for a named pipe interprocess communication (based on the NCBI CNamedPipe).
Implement CONNECTOR for a pipe interprocess communication (based on the NCBI CPipe).
int offset
Definition: replacements.h:160
Connector specification.
Helper class to fetch HTTP status code and text.
Timeout structure.
Definition: ncbi_types.h:76
Definition: inftrees.h:24
Definition: type.c:6
static const struct type types[]
Definition: type.c:22
string ToString(const wxRect &rc)
Definition: wx_utils.cpp:773
Modified on Sat Dec 09 04:46:30 2023 by modify_doxy.py rev. 669887