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

Go to the SVN repository for this file.

1 #ifndef CGI___CGIAPP__HPP
2 #define CGI___CGIAPP__HPP
3 
4 /* $Id: cgiapp.hpp 98307 2022-10-26 16:12:23Z grichenk $
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:
30 * Vsevolod Sandomirskiy, Aaron Ucko, Denis Vakatov, Anatoliy Kuznetsov
31 *
32 * File Description:
33 * Base class for (Fast-)CGI applications
34 */
35 
36 #include <corelib/ncbireg.hpp>
37 #include <corelib/ncbiapp.hpp>
38 #include <cgi/ncbires.hpp>
39 #include <cgi/caf.hpp>
40 
41 
42 /** @addtogroup CGIBase
43  *
44  * @{
45  */
46 
47 
49 
50 class CCgiServerContext;
51 class CCgiStatistics;
52 class CCgiWatchFile;
53 class ICgiSessionStorage;
55 class ICache;
57 
58 /////////////////////////////////////////////////////////////////////////////
59 // CCgiApplication::
60 //
61 
63 {
64  friend class CCgiStatistics;
65  friend class CCgiRequestProcessor;
66  friend void s_ScheduleFastCGIExit(void);
67 
68 public:
70 
71  CCgiApplication(const SBuildInfo& build_info = NCBI_SBUILDINFO_DEFAULT());
72  ~CCgiApplication(void);
73 
74  /// Singleton
75  static CCgiApplication* Instance(void);
76 
77  /// Get current server context. Throw exception if the context is not set.
78  const CCgiContext& GetContext(void) const { return x_GetContext(); }
79  /// Get current server context. Throw exception if the context is not set.
80  CCgiContext& GetContext(void) { return x_GetContext(); }
81 
82  /// Get server 'resource'. Throw exception if the resource is not set.
83  const CNcbiResource& GetResource(void) const { return x_GetResource(); }
84  /// Get server 'resource'. Throw exception if the resource is not set.
85  CNcbiResource& GetResource(void) { return x_GetResource(); }
86 
87  /// Get the # of currently processed HTTP request.
88  ///
89  /// 1-based for FastCGI (but 0 before the first iteration starts);
90  /// always 0 for regular (i.e. not "fast") CGIs.
91  unsigned int GetFCgiIteration(void) const { return (unsigned int)(m_Iteration.Get()); }
92 
93  /// Return TRUE if it is running as a "fast" CGI
94  virtual bool IsFastCGI(void) const;
95 
96  /// This method is called on the CGI application initialization -- before
97  /// starting to process a HTTP request or even receiving one.
98  ///
99  /// No HTTP request (or context) is available at the time of call.
100  ///
101  /// If you decide to override it, remember to call CCgiApplication::Init().
102  virtual void Init(void);
103 
104  /// This method is called on the CGI application exit.
105  ///
106  /// No HTTP request (or context) is available at the time of call.
107  ///
108  /// If you decide to override it, remember to call CCgiApplication::Exit().
109  virtual void Exit(void);
110 
111  /// Do not override this method yourself! -- it includes all the CGI
112  /// specific machinery. If you override it, do call CCgiApplication::Run()
113  /// from inside your overriding method.
114  /// @sa ProcessRequest
115  virtual int Run(void);
116 
117  /// This is the method you should override. It is called whenever the CGI
118  /// application gets a syntaxically valid HTTP request.
119  /// @param context
120  /// Contains the parameters of the HTTP request
121  /// @return
122  /// Exit code; it must be zero on success
123  virtual int ProcessRequest(CCgiContext& context) = 0;
124 
125  virtual CNcbiResource* LoadResource(void);
126  virtual CCgiServerContext* LoadServerContext(CCgiContext& context);
127 
128  /// Set cgi parsing flag
129  /// @sa CCgiRequest::Flags
130  void SetRequestFlags(int flags) { m_RequestFlags = flags; }
131 
132  virtual void SetupArgDescriptions(CArgDescriptions* arg_desc);
133 
134  /// Get parsed command line arguments extended with CGI parameters
135  ///
136  /// @return
137  /// The CArgs object containing parsed cmd.-line arguments and
138  /// CGI parameters
139  ///
140  virtual const CArgs& GetArgs(void) const;
141 
142  /// Get instance of CGI session storage interface.
143  /// If the CGI application needs to use CGI session it should overwrite
144  /// this metod and return an instance of an implementation of
145  /// ICgiSessionStorage interface.
146  /// @param params
147  /// Optional parameters
148  virtual ICgiSessionStorage* GetSessionStorage(CCgiSessionParameters& params) const;
149 
150  /// Validate synchronization token (cross-site request forgery prevention).
151  /// CSRF prevention is controlled by CGI_VALIDATE_CSRF_TOKEN variable (bool).
152  /// The default implementation assumes the token is passed in Ncbi-CSRF-Token
153  /// HTTP header and must be equal to the current session id.
154  /// @return
155  /// - true if the token passes validation or if CSRF prevention is disabled.
156  /// - false if the token does not pass validation; the CGI will return
157  /// status "403 Forbidden".
158  /// @sa CCgiSession
159  virtual bool ValidateSynchronizationToken(void);
160 
161 protected:
162  /// Check the command line arguments before parsing them.
163  /// If '-version' or '-version-full' is the only argument,
164  /// print the version and exit (return ePreparse_Exit). Otherwise
165  /// return ePreparse_Continue for normal execution.
166  virtual EPreparseArgs PreparseArgs(int argc,
167  const char* const* argv);
168 
169  void SetRequestId(const string& rid, bool is_done);
170 
171  /// This method is called if an exception is thrown during the processing
172  /// of HTTP request. OnEvent() will be called after this method.
173  ///
174  /// Context and Resource aren't valid at the time of this method call
175  ///
176  /// The default implementation sends out an HTTP response with "e.what()",
177  /// and then returns zero if the printout has got through, -1 otherwise.
178  /// @param e
179  /// The exception thrown
180  /// @param os
181  /// Output stream to the client.
182  /// @return
183  /// Value to use as the CGI's (or FCGI iteration's) exit code
184  /// @sa OnEvent
185  virtual int OnException(std::exception& e, CNcbiOstream& os);
186 
187  /// @sa OnEvent, ProcessRequest
188  enum EEvent {
190  eSuccess, ///< The HTTP request was processed, with zero exit code
191  eError, ///< The HTTP request was processed, non-zero exit code
192  eWaiting, ///< Periodic awakening while waiting for the next request
193  eException, ///< An exception occured during the request processing
194  eEndRequest, ///< HTTP request processed, all results sent to client
195  eExit, ///< No more iterations, exiting (called the very last)
196  eExecutable, ///< FCGI forced to exit as its modif. time has changed
197  eWatchFile, ///< FCGI forced to exit as its "watch file" has changed
198  eExitOnFail, ///< [FastCGI].StopIfFailed set, and the iteration failed
199  eExitRequest ///< FCGI forced to exit by client's 'exitfastcgi' request
200  };
201 
202  /// This method is called after each request, or when the CGI is forced to
203  /// skip a request, or to finish altogether without processing a request.
204  ///
205  /// No HTTP request (or context) may be available at the time of call.
206  ///
207  /// The default implementation of this method does nothing.
208  ///
209  /// @param event
210  /// CGI framework event
211  /// @param status
212  /// - eSuccess, eError: the value returned by ProcessRequest()
213  /// - eException: the value returned by OnException()
214  /// - eExit: exit code of the CGI application
215  /// - others: non-zero, and different for any one status
216  virtual void OnEvent(EEvent event, int status);
217 
218  /// Schedule Fast-CGI loop to end as soon as possible, after
219  /// safely finishing the currently processed request, if any.
220  /// @note
221  /// Calling it from inside OnEvent(eWaiting) will end the Fast-CGI
222  /// loop immediately.
223  /// @note
224  /// It is a no-op for the regular CGI.
225  virtual void FASTCGI_ScheduleExit(void) { m_ShouldExit = true; }
226 
227  /// Factory method for the Context object construction
228  virtual CCgiContext* CreateContext(CNcbiArguments* args = 0,
229  CNcbiEnvironment* env = 0,
230  CNcbiIstream* inp = 0,
231  CNcbiOstream* out = 0,
232  int ifd = -1,
233  int ofd = -1);
234 
235  /// The same as CreateContext(), but allows for a custom set of flags
236  /// to be specified in the CCgiRequest constructor.
237  virtual CCgiContext* CreateContextWithFlags(CNcbiArguments* args,
239  int ifd, int ofd, int flags);
240 
241  /// Default implementation of CreateContextWithFlags.
242  CCgiContext* CreateContextWithFlags_Default(CCgiRequestProcessor& processor,
244  int ifd, int ofd, int flags);
245 
246  void RegisterDiagFactory(const string& key,
247  CDiagFactory* fact);
248  CDiagFactory* FindDiagFactory(const string& key);
249 
250  virtual void ConfigureDiagnostics (CCgiContext& context);
251  virtual void ConfigureDiagDestination(CCgiContext& context);
252  virtual void ConfigureDiagThreshold (CCgiContext& context);
253  virtual void ConfigureDiagFormat (CCgiContext& context);
254 
255  /// Analyze registry settings ([CGI] Log) and return current logging option
256  enum ELogOpt {
259  eLogOnError
260  };
261  ELogOpt GetLogOpt(void) const;
262 
263  /// Class factory for statistics class
264  virtual CCgiStatistics* CreateStat();
265 
266  /// Attach cookie affinity service interface. Pointer ownership goes to
267  /// the CCgiApplication.
268  void SetCafService(CCookieAffinity* caf);
269 
270  /// Check CGI context for possible problems, throw exception with
271  /// HTTP status set if something is wrong.
272  void VerifyCgiContext(CCgiContext& context);
273 
274  /// Get default path for the log files.
275  virtual string GetDefaultLogPath(void) const;
276 
277  /// Prepare properties and print the application start message
278  virtual void AppStart(void);
279  /// Prepare properties for application stop message
280  virtual void AppStop(int exit_code);
281 
282  /// Set HTTP status code in the current request context and in the
283  /// current CHttpResponse if one exists.
284  /// @sa CHttpResponse::SetStatus()
285  void SetHTTPStatus(unsigned int status, const string& reason = kEmptyStr);
286 
287  /// Process help request: set content type, print usage informations etc.
288  /// For automatic handling of help request all of the following conditions
289  /// must be met:
290  /// - CGI_ENABLE_HELP_REQUEST=t must be set in the environment or
291  /// EnableHelpRequest=t in [CGI] section of the INI file.
292  /// - REQUEST_METHOD must be GET
293  /// - query string must include ncbi_help[=<format>] argument (all other
294  /// arguments are ignored).
295  /// The default implementation looks for <appname>.help.<format> files in
296  /// the app directory, then for help.<format>. The formats are checked in
297  /// the following order:
298  /// 1. If format argument is present, try to open <appname>.help.<format>,
299  /// then help.<format>.
300  /// 2. Check 'Accept:' http header; for each 'type/subtype' entry try to open
301  /// <appname>.help.<subtype> and help.<subtype>.
302  /// 3. Check availability of help files for html, xml, and json formats.
303  /// 4. Use CArgDescriptions to print help in XML format.
304  /// If a help file starts with 'Content-type: ...' followed by double-
305  /// newline, the specified content type is sent in the response regardless
306  /// of the actual format selected.
307  virtual void ProcessHelpRequest(const string& format);
308 
311  eVersion_Full
312  };
313 
314  /// Process version request: set content type, print version informations etc.
315  /// For automatic handling of version request all of the following conditions
316  /// must be met:
317  /// - CGI_ENABLE_VERSION_REQUEST=t must be set in the environment or
318  /// EnableVersionRequest=t in [CGI] section of the INI file.
319  /// - REQUEST_METHOD must be GET
320  /// - query string must include ncbi_version=[short|full] argument (all other
321  /// arguments are ignored).
322  /// The default implementation prints GetVersion/GetFullVersion as plain text
323  /// (default), XML or JSON depending on the 'Accept:' HTTP header, if any.
324  virtual void ProcessVersionRequest(EVersionType ver_type);
325 
326  /// Admin commands passed through ncbi_admin_cmd argument.
328  eAdmin_Health, ///< Report health for this CGI only
329  eAdmin_HealthDeep, ///< Report health for this CGI and any services used by it.
330  eAdmin_Unknown ///< Unrecognized command. Overriden ProcessAdminRequest()
331  ///< can use GetEntry() to fetch command name if necessary.
332  };
333 
334  /// Process admin command passed through ncbi_admin_cmd argument.
335  /// Return true on success, false if the command was not processed
336  /// (in this case the default processing will be used).
337  virtual bool ProcessAdminRequest(EAdminCommand cmd);
338 
339  /// "Accept:" header entry.
340  struct SAcceptEntry {
341  SAcceptEntry(void) : m_Quality(1) {}
342 
344 
345  string m_Type;
346  string m_Subtype;
347  float m_Quality; ///< Quality factor or "1" if not set (or not numeric).
348  string m_MediaRangeParams; ///< Media range parameters
349  TParams m_AcceptParams; ///< Accept parameters
350 
351  bool operator<(const SAcceptEntry& entry) const;
352  };
353 
354  typedef list<SAcceptEntry> TAcceptEntries;
355 
356  /// Parse "Accept:" header, put entries to the list, more specific first.
357  void ParseAcceptHeader(TAcceptEntries& entries) const;
358 
359  /// Create request processor to process the request. If the method returns null,
360  /// the application's ProcessRequest() method is used for the request. Otherwise
361  /// request is passed to the processor.
362  /// @sa CCgiRequestProcessor
363  virtual CCgiRequestProcessor* CreateRequestProcessor(void);
364 
365 protected:
366  /// Set CONN_HTTP_REFERER, print self-URL and referer to log.
367  void ProcessHttpReferer(void);
368 
369  /// @deprecated Use LogRequest(const CCgiContext&) instead.
370  NCBI_DEPRECATED void LogRequest(void) const;
371  /// Write the required values to log (user-agent, self-url, referer etc.)
372  void LogRequest(const CCgiContext& ctx) const;
373 
374  /// Bit flags for CCgiRequest
376 
377  // If FastCGI-capable, and run as a Fast-CGI, then iterate through
378  // the FastCGI loop (doing initialization and running ProcessRequest()
379  // for each HTTP request); then return TRUE.
380  // Return FALSE overwise.
381  // In the "result", return # of requests whose processing has failed
382  // (exception was thrown or ProcessRequest() returned non-zero value)
383  virtual bool x_RunFastCGI(int* result, unsigned int def_iter = 10);
384 
385  string GetFastCGIStandaloneServer(void) const;
386  bool GetFastCGIStatLog(void) const;
387  unsigned int GetFastCGIIterations(unsigned int def_iter) const;
388  bool GetFastCGIComplete_Request_On_Sigterm(void) const;
389  CCgiWatchFile* CreateFastCGIWatchFile(void) const;
390  unsigned int GetFastCGIWatchFileTimeout(bool have_watcher) const;
391  int GetFastCGIWatchFileRestartDelay(void) const;
392  bool GetFastCGIChannelErrors(void) const;
393  bool GetFastCGIHonorExitRequest(void) const;
394  bool GetFastCGIDebug(void) const;
395  bool GetFastCGIStopIfFailed(void) const;
396  unsigned int GetFastCGIMTMaxThreads(void) const;
397 
398  static CTime GetFileModificationTime(const string& filename);
399  // Return true if current memory usage is above the limit.
400  bool CheckMemoryLimit(void);
401  void InitArgs(CArgs& args, CCgiContext& context) const;
402  void AddLBCookie(CCgiCookies& cookies);
403  virtual ICache* GetCacheStorage(void) const;
404  virtual bool IsCachingNeeded(const CCgiRequest& request) const;
405  bool GetResultFromCache(const CCgiRequest& request, CNcbiOstream& os, ICache& cache);
406  void SaveResultToCache(const CCgiRequest& request, CNcbiIstream& is, ICache& cache);
407  void SaveRequest(const string& rid, const CCgiRequest& request, ICache& cache);
408  CCgiRequest* GetSavedRequest(const string& rid, ICache& cache);
409  bool x_ProcessHelpRequest(CCgiRequestProcessor& processor);
410  bool x_ProcessVersionRequest(CCgiRequestProcessor& processor);
411  bool x_ProcessAdminRequest(CCgiRequestProcessor& processor);
412 
414  eSR_None = 0,
415  eSR_Executable = 111,
416  eSR_WatchFile = 112
417  };
418  // Decide if this FastCGI process should be finished prematurely, right now
419  // (the criterion being whether the executable or a special watched file
420  // has changed since the last iteration)
421  // NOTE: The method is not MT-safe.
422  static ERestartReason ShouldRestart(CTime& mtime, CCgiWatchFile* watcher, int delay);
423 
424  // Write message to the application log, call OnEvent()
425  void x_OnEvent(CCgiRequestProcessor* pprocessor, EEvent event, int status);
426  // Backward compatibility
427  void x_OnEvent(EEvent event, int status) { x_OnEvent(x_GetProcessorOrNull(), event, status); }
428 
429  // Create processor and store it in TLS.
430  CCgiRequestProcessor& x_CreateProcessor(void);
431 
434  CAtomicCounter m_Iteration; // (always 0 for plain CGI)
435 
436 private:
437 
438  // Add cookie with load balancer information
439  void x_AddLBCookie();
440 
441  CCgiContext& x_GetContext (void) const;
442  CNcbiResource& x_GetResource(void) const;
443  bool x_IsSetProcessor(void) const;
444  CCgiRequestProcessor& x_GetProcessor(void) const;
445  CCgiRequestProcessor* x_GetProcessorOrNull(void) const;
446 
447  // Check if HEAD request has been served.
448  bool x_DoneHeadRequest(CCgiContext& context) const;
449 
450  unique_ptr<CNcbiResource> m_Resource;
451 
454 
455  unique_ptr<CCookieAffinity> m_Caf; // Cookie affinity service pointer
456  char* m_HostIP; // Cookie affinity host IP buffer
457 
458  // Environment var. value to put to the diag.prefix; [CGI].DiagPrefixEnv
460 
461  /// @sa FASTCGI_ScheduleExit()
462  bool m_ShouldExit = false;
463 
464  // forbidden
467 };
468 
469 
470 /////////////////////////////////////////////////////////////////////////////
471 // CCgiStatistics::
472 //
473 // CGI statistics information
474 //
475 
477 {
478  friend class CCgiApplication;
479  friend class CFastCgiApplicationMT;
480 public:
481  virtual ~CCgiStatistics();
482 
483 protected:
485 
486  // Reset statistics class. Method called only ones for CGI
487  // applications and every iteration if it is FastCGI.
488  virtual void Reset(const CTime& start_time,
489  int result,
490  const std::exception* ex = 0);
491 
492  // Compose message for statistics logging.
493  // This default implementation constructs the message from the fragments
494  // composed with the help of "Compose_Xxx()" methods (see below).
495  // NOTE: It can return empty string (when time cut-off is engaged).
496  virtual string Compose(void);
497 
498  // Log the message
499  virtual void Submit(const string& message);
500 
501 protected:
502  virtual string Compose_ProgramName (void);
503  virtual string Compose_Timing (const CTime& end_time);
504  virtual string Compose_Entries (void);
505  virtual string Compose_Result (void);
506  virtual string Compose_ErrMessage (void);
507 
508 protected:
509  CCgiApplication& m_CgiApp; // Reference on the "mother app"
510  string m_LogDelim; // Log delimiter
511  CTime m_StartTime; // CGI start time
512  int m_Result; // Return code
513  string m_ErrMsg; // Error message
514 };
515 
516 
517 /////////////////////////////////////////////////////////////////////////////
518 // CCgiWatchFile::
519 //
520 // Aux. class for noticing changes to a file
521 //
522 
524 {
525 public:
526  // ignores changes after the first LIMIT bytes
527  CCgiWatchFile(const string& filename, int limit = 1024);
528  bool HasChanged(void);
529 
530 private:
532 
533  string m_Filename;
534  int m_Limit;
535  int m_Count;
537 
538  // returns count of bytes read (up to m_Limit), or -1 if opening failed.
539  int x_Read(char* buf);
540 };
541 
542 
543 /////////////////////////////////////////////////////////////////////////////
544 // CCgiStreamWrapper::
545 //
546 // CGI stream with special processing.
547 //
548 
550 
552 {
553 public:
554  enum EStreamMode {
555  eNormal, // normal output - write all data as-is
556  eBlockWrites, // block all writes after HEAD request
557  eChunkedWrites, // chunked output mode
558  };
559 
561 
563 
564  // Access to writer's methods.
567  void SetCacheStream(CNcbiOstream& stream);
568  void FinishChunkedTransfer(const TTrailer* trailer);
569  void AbortChunkedTransfer(void);
570 
571 private:
573 };
574 
575 
576 /// Base class for request processors.
577 /// @sa CCgiApplication::CreateRequestProcessor()
579 {
580  friend class CCgiApplication;
581 
582 public:
584  virtual ~CCgiRequestProcessor(void);
585 
586  /// Process request provided by the context. By default calls application's ProcessRequest.
587  virtual int ProcessRequest(CCgiContext& context);
588 
589  const CNcbiResource& GetResource(void) const { return m_App.GetResource(); }
590  CNcbiResource& GetResource(void) { return m_App.GetResource(); }
591 
592  virtual bool ValidateSynchronizationToken(void);
593 
594  /// Get self-URL to be used as referer.
595  string GetSelfReferer(void) const;
596 
597 protected:
598  virtual void ProcessHelpRequest(const string& format);
601  virtual int OnException(std::exception& e, CNcbiOstream& os);
602  virtual void OnEvent(CCgiApplication::EEvent event, int status);
603 
604  void SetHTTPStatus(unsigned int status, const string& reason = kEmptyStr);
605  void SetRequestId(const string& rid, bool is_done);
606 
610 
611 private:
612  void x_InitArgs(void) const;
613  // If ProcessAdminRequest is overridden, the base method may still be called.
614  bool ProcessAdminRequest_Base(CCgiApplication::EAdminCommand cmd);
615 
617  shared_ptr<CCgiContext> m_Context;
618  // Parsed cmd.-line args (cmdline + CGI).
619  mutable unique_ptr<CArgs> m_CgiArgs;
620  // Wrappers for cin and cout
621  unique_ptr<CNcbiIstream> m_InputStream;
622  unique_ptr<CNcbiOstream> m_OutputStream;
623  bool m_OutputBroken = false;
624  // Remember if request-start was printed, don't print request-stop
625  // without request-start.
626  bool m_RequestStartPrinted = false;
627  bool m_ErrorStatus = false; // True if HTTP status was set to a value >=400
628  string m_RID;
629  bool m_IsResultReady = true;
630 
631 public:
632  CCgiApplication& GetApp(void) { return m_App; }
633  const CCgiApplication& GetApp(void) const { return m_App; }
634 
635  CCgiContext& GetContext(void) { return *m_Context; }
636  const CCgiContext& GetContext(void) const { return *m_Context; }
637  void SetContext(shared_ptr<CCgiContext> context) { m_Context = context; }
638  bool IsSetContext(void) const { return bool(m_Context); }
639 
640  CArgs& GetArgs(void) { if (!m_CgiArgs) x_InitArgs(); return *m_CgiArgs; }
641  const CArgs& GetArgs(void) const { if (!m_CgiArgs) x_InitArgs(); return *m_CgiArgs; }
642  bool IsSetArgs(void) const { return bool(m_CgiArgs); }
643 
644  CNcbiIstream& GetInputStream(void) { return *m_InputStream; }
645  const CNcbiIstream& GetInputStream(void) const { return *m_InputStream; }
646  void SetInputStream(CNcbiIstream* in) { m_InputStream.reset(in); }
647  bool IsSetInputStream(void) const { return bool(m_InputStream); }
648 
649  CNcbiOstream& GetOutputStream(void) { return *m_OutputStream; }
650  const CNcbiOstream& GetOutputStream(void) const { return *m_OutputStream; }
651  void SetOutputStream(CNcbiOstream* out) { m_OutputStream.reset(out); }
652  bool IsSetOutputStream(void) const { return bool(m_OutputStream); }
653 
654  bool GetOutputBroken(void) const { return m_OutputBroken; }
655  void SetOutputBroken(bool val) { m_OutputBroken = val; }
656 
657  bool GetRequestStartPrinted(void) const { return m_RequestStartPrinted; }
658  void SetRequestStartPrinted(bool val) { m_RequestStartPrinted = val; }
659 
660  bool GetErrorStatus(void) const { return m_ErrorStatus; }
661  void SetErrorStatus(bool val) { m_ErrorStatus = val; }
662 
663  string GetRID(void) const { return m_RID; }
664  void SetRID(const string& val) { m_RID = val; }
665 
666  bool GetResultReady(void) const { return m_IsResultReady; }
667  void SetResultReady(bool val) { m_IsResultReady = val; }
668 };
669 
670 
671 // Aux. class to provide timely reset of "m_Processor" in RunFastCGI()
673 {
674 public:
677 private:
679 };
680 
681 
682 /////////////////////////////////////////////////////////////////////////////
683 // Tracking Environment
684 
686 typedef NCBI_PARAM_TYPE(CGI, DisableTrackingCookie) TCGI_DisableTrackingCookie;
688 typedef NCBI_PARAM_TYPE(CGI, TrackingCookieName) TCGI_TrackingCookieName;
690 typedef NCBI_PARAM_TYPE(CGI, TrackingTagName) TCGI_TrackingTagName;
692 typedef NCBI_PARAM_TYPE(CGI, TrackingCookieDomain) TCGI_TrackingCookieDomain;
694 typedef NCBI_PARAM_TYPE(CGI, TrackingCookiePath) TCGI_TrackingCookiePath;
698  TClientConnIntOk;
702  TClientConnIntSeverity;
703 
705 
706 
707 /* @} */
708 
709 
710 #endif // CGI___CGIAPP__HPP
AutoPtr –.
Definition: ncbimisc.hpp:401
CArgDescriptions –.
Definition: ncbiargs.hpp:541
CArgs –.
Definition: ncbiargs.hpp:379
CAtomicCounter –.
Definition: ncbicntr.hpp:71
CCgiCookies::
Definition: ncbicgi.hpp:219
Base class for request processors.
Definition: cgiapp.hpp:579
CCgiRequest::
Definition: ncbicgi.hpp:685
CDiagFactory –.
Definition: ncbidiag.hpp:2925
static CNcbiApplication * Instance(void)
Singleton method.
Definition: ncbiapp.cpp:264
CNcbiArguments –.
Definition: ncbienv.hpp:236
CNcbiEnvironment –.
Definition: ncbienv.hpp:110
CRef –.
Definition: ncbiobj.hpp:618
CTime –.
Definition: ncbitime.hpp:296
Writer-based output stream.
Definition: rwstream.hpp:171
BLOB cache read/write/maintenance interface.
Definition: icache.hpp:64
ICgiSessionStorage –.
static uch flags
bool operator<(const CEquivRange &A, const CEquivRange &B)
std::ofstream out("events_result.xml")
main entry point for tests
static CS_COMMAND * cmd
Definition: ct_dynamic.c:26
CS_CONTEXT * ctx
Definition: t0006.c:12
static time_t start_time
Definition: timeout.c:14
static const char * proc
Definition: stats.c:21
static HENV env
Definition: transaction2.c:38
void LogRequest(const TReq &req)
virtual EPreparseArgs PreparseArgs(int argc, const char *const *argv)
Check the command line arguments before parsing them.
Definition: ncbiapp.cpp:1299
virtual int Run(void)=0
Run the application.
virtual void Init(void)
Initialize the application.
Definition: ncbiapp.cpp:286
virtual void AppStop(int exit_code)
Method to be called before application exit.
Definition: ncbiapp.cpp:1758
virtual const CArgs & GetArgs(void) const
Get parsed command line arguments.
Definition: ncbiapp.cpp:305
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
Definition: ncbiapp.cpp:1195
virtual void Exit(void)
Cleanup on application exit.
Definition: ncbiapp.cpp:299
virtual void AppStart(void)
Method to be called before application start.
Definition: ncbiapp.cpp:1738
void SetHTTPStatus(unsigned int status, const string &reason=kEmptyStr)
Definition: cgiapp.cpp:2565
EAdminCommand
Admin commands passed through ncbi_admin_cmd argument.
Definition: cgiapp.hpp:327
~CCgiProcessorGuard(void)
Definition: cgiapp.hpp:676
virtual int OnException(std::exception &e, CNcbiOstream &os)
This method is called if an exception is thrown during the processing of HTTP request.
Definition: cgiapp.cpp:1059
AutoPtr< char, ArrayDeleter< char > > TBuf
Definition: cgiapp.hpp:531
const CNcbiResource & GetResource(void) const
Definition: cgiapp.hpp:589
bool GetRequestStartPrinted(void) const
Definition: cgiapp.hpp:657
void SetOutputBroken(bool val)
Definition: cgiapp.hpp:655
const CCgiContext & GetContext(void) const
Get current server context. Throw exception if the context is not set.
Definition: cgiapp.hpp:78
void SetRequestStartPrinted(bool val)
Definition: cgiapp.hpp:658
TrackingCookieName
Definition: cgiapp.hpp:687
map< string, string, PNocase > TTrailer
Definition: cgiapp.hpp:562
void SetErrorStatus(bool val)
Definition: cgiapp.hpp:661
string m_Filename
Definition: cgiapp.hpp:533
shared_ptr< CCgiContext > m_Context
Definition: cgiapp.hpp:617
string m_LogDelim
Definition: cgiapp.hpp:510
CCgiStreamWrapperWriter * m_Writer
Definition: cgiapp.hpp:572
bool GetOutputBroken(void) const
Definition: cgiapp.hpp:654
void SetRequestFlags(int flags)
Set cgi parsing flag.
Definition: cgiapp.hpp:130
void AbortChunkedTransfer(void)
Definition: cgiapp.cpp:446
const CNcbiOstream & GetOutputStream(void) const
Definition: cgiapp.hpp:650
friend class CCgiRequestProcessor
Definition: cgiapp.hpp:65
CAtomicCounter m_Iteration
Definition: cgiapp.hpp:434
virtual void ProcessVersionRequest(CCgiApplication::EVersionType ver_type)
Definition: cgiapp.cpp:2380
unique_ptr< CNcbiOstream > m_OutputStream
Definition: cgiapp.hpp:622
CTime m_StartTime
Definition: cgiapp.hpp:511
char * m_HostIP
Definition: cgiapp.hpp:456
int x_Read(char *buf)
Definition: cgiapp.cpp:2212
typedef NCBI_PARAM_TYPE(CGI, DisableTrackingCookie) TCGI_DisableTrackingCookie
string m_MediaRangeParams
Media range parameters.
Definition: cgiapp.hpp:348
int m_RequestFlags
Bit flags for CCgiRequest.
Definition: cgiapp.hpp:375
bool HasChanged(void)
Definition: cgiapp.cpp:2232
CCgiContext & GetContext(void)
Get current server context. Throw exception if the context is not set.
Definition: cgiapp.hpp:80
CCgiProcessorGuard(CTls< CCgiRequestProcessor > &proc)
Definition: cgiapp.hpp:675
CArgs & GetArgs(void)
Definition: cgiapp.hpp:640
void SetRID(const string &val)
Definition: cgiapp.hpp:664
virtual bool ProcessAdminRequest(CCgiApplication::EAdminCommand cmd)
Definition: cgiapp.cpp:2436
bool IsSetArgs(void) const
Definition: cgiapp.hpp:642
CCgiApplication(const CCgiApplication &)
CCgiApplication::SAcceptEntry TAcceptEntry
Definition: cgiapp.hpp:608
void SetInputStream(CNcbiIstream *in)
Definition: cgiapp.hpp:646
unique_ptr< CNcbiResource > m_Resource
Definition: cgiapp.hpp:450
CCgiWatchFile(const string &filename, int limit=1024)
Definition: cgiapp.cpp:2223
void SetCacheStream(CNcbiOstream &stream)
Definition: cgiapp.cpp:434
virtual void OnEvent(EEvent event, int status)
This method is called after each request, or when the CGI is forced to skip a request,...
Definition: cgiapp.cpp:1202
CNcbiOstream & GetOutputStream(void)
Definition: cgiapp.hpp:649
virtual void OnEvent(CCgiApplication::EEvent event, int status)
Definition: cgiapp.cpp:2559
virtual void ProcessHelpRequest(const string &format)
Definition: cgiapp.cpp:2270
float m_Quality
Quality factor or "1" if not set (or not numeric).
Definition: cgiapp.hpp:347
bool GetErrorStatus(void) const
Definition: cgiapp.hpp:660
map< string, string > TParams
Definition: cgiapp.hpp:343
friend void s_ScheduleFastCGIExit(void)
CTls< CCgiRequestProcessor > * m_Proc
Definition: cgiapp.hpp:678
CCgiApplication & m_App
Definition: cgiapp.hpp:616
EStreamMode GetWriterMode(void)
Definition: cgiapp.cpp:421
void x_OnEvent(EEvent event, int status)
Definition: cgiapp.hpp:427
DisableTrackingCookie
Definition: cgiapp.hpp:685
const CCgiApplication & GetApp(void) const
Definition: cgiapp.hpp:633
virtual bool ProcessAdminRequest(EAdminCommand cmd)
Process admin command passed through ncbi_admin_cmd argument.
Definition: cgiapp.cpp:1810
friend class CCgiApplication
Definition: cgiapp.hpp:580
void SetRequestId(const string &rid, bool is_done)
Definition: cgiapp.cpp:2576
CNcbiApplication CParent
Definition: cgiapp.hpp:69
void SetHTTPStatus(unsigned int status, const string &reason=kEmptyStr)
Set HTTP status code in the current request context and in the current CHttpResponse if one exists.
Definition: cgiapp.cpp:1634
CNcbiResource & GetResource(void)
Definition: cgiapp.hpp:590
unique_ptr< CCookieAffinity > m_Caf
Definition: cgiapp.hpp:455
CCgiApplication::TAcceptEntries TAcceptEntries
Definition: cgiapp.hpp:607
virtual int OnException(std::exception &e, CNcbiOstream &os)
Definition: cgiapp.cpp:2482
void SetWriterMode(EStreamMode mode)
Definition: cgiapp.cpp:427
bool IsSetOutputStream(void) const
Definition: cgiapp.hpp:652
virtual void FASTCGI_ScheduleExit(void)
Schedule Fast-CGI loop to end as soon as possible, after safely finishing the currently processed req...
Definition: cgiapp.hpp:225
TrackingTagName
Definition: cgiapp.hpp:689
virtual bool ValidateSynchronizationToken(void)
Definition: cgiapp.cpp:2456
CCgiApplication & GetApp(void)
Definition: cgiapp.hpp:632
NCBI_XCGI_EXPORT
Definition: cgiapp.hpp:685
string GetRID(void) const
Definition: cgiapp.hpp:663
TDiagFactoryMap m_DiagFactories
Definition: cgiapp.hpp:453
TrackingCookiePath
Definition: cgiapp.hpp:693
ELogOpt
Analyze registry settings ([CGI] Log) and return current logging option.
Definition: cgiapp.hpp:256
virtual bool ValidateSynchronizationToken(void)
Validate synchronization token (cross-site request forgery prevention).
Definition: cgiapp.cpp:1823
const CArgs & GetArgs(void) const
Definition: cgiapp.hpp:641
const CCgiContext & GetContext(void) const
Definition: cgiapp.hpp:636
friend class CCgiStatistics
Definition: cgiapp.hpp:64
string m_DiagPrefixEnv
Definition: cgiapp.hpp:459
void SetRequestId(const string &rid, bool is_done)
Definition: cgiapp.cpp:1412
virtual void ProcessHelpRequest(const string &format)
Process help request: set content type, print usage informations etc.
Definition: cgiapp.cpp:1719
bool IsSetInputStream(void) const
Definition: cgiapp.hpp:647
CNcbiResource & GetResource(void)
Get server 'resource'. Throw exception if the resource is not set.
Definition: cgiapp.hpp:85
void SetContext(shared_ptr< CCgiContext > context)
Definition: cgiapp.hpp:637
CCgiApplication & m_CgiApp
Definition: cgiapp.hpp:509
string m_ErrMsg
Definition: cgiapp.hpp:513
const CNcbiResource & GetResource(void) const
Get server 'resource'. Throw exception if the resource is not set.
Definition: cgiapp.hpp:83
void SetOutputStream(CNcbiOstream *out)
Definition: cgiapp.hpp:651
const CNcbiIstream & GetInputStream(void) const
Definition: cgiapp.hpp:645
bool IsSetContext(void) const
Definition: cgiapp.hpp:638
virtual void ProcessVersionRequest(EVersionType ver_type)
Process version request: set content type, print version informations etc.
Definition: cgiapp.cpp:1776
CCgiContext & GetContext(void)
Definition: cgiapp.hpp:635
void SetResultReady(bool val)
Definition: cgiapp.hpp:667
unsigned int GetFCgiIteration(void) const
Get the # of currently processed HTTP request.
Definition: cgiapp.hpp:91
list< SAcceptEntry > TAcceptEntries
Definition: cgiapp.hpp:354
CRef< CTls< CCgiRequestProcessor > > m_Processor
Definition: cgiapp.hpp:433
Client_Connection_Interruption_Okay
Definition: cgiapp.hpp:696
virtual int ProcessRequest(CCgiContext &context)=0
This is the method you should override.
void ParseAcceptHeader(TAcceptEntries &entries) const
Parse "Accept:" header, put entries to the list, more specific first.
Definition: cgiapp.cpp:1683
map< string, CDiagFactory * > TDiagFactoryMap
Definition: cgiapp.hpp:452
unique_ptr< CArgs > m_CgiArgs
Definition: cgiapp.hpp:619
bool m_CaughtSigterm
Definition: cgiapp.hpp:432
CCgiStreamWrapper(CNcbiOstream &out)
Definition: cgiapp.cpp:414
Client_Connection_Interruption_Severity
Definition: cgiapp.hpp:700
CNcbiIstream & GetInputStream(void)
Definition: cgiapp.hpp:644
bool GetResultReady(void) const
Definition: cgiapp.hpp:666
CCgiApplication & operator=(const CCgiApplication &)
TParams m_AcceptParams
Accept parameters.
Definition: cgiapp.hpp:349
void FinishChunkedTransfer(const TTrailer *trailer)
Definition: cgiapp.cpp:440
bool
Definition: cgiapp.hpp:685
TrackingCookieDomain
Definition: cgiapp.hpp:691
unique_ptr< CNcbiIstream > m_InputStream
Definition: cgiapp.hpp:621
CGI
Definition: cgiapp.hpp:685
@ eAdmin_Health
Report health for this CGI only.
Definition: cgiapp.hpp:328
@ eAdmin_HealthDeep
Report health for this CGI and any services used by it.
Definition: cgiapp.hpp:329
@ eException
An exception occured during the request processing.
Definition: cgiapp.hpp:193
@ eExit
No more iterations, exiting (called the very last)
Definition: cgiapp.hpp:195
@ eWaiting
Periodic awakening while waiting for the next request.
Definition: cgiapp.hpp:192
@ eError
The HTTP request was processed, non-zero exit code.
Definition: cgiapp.hpp:191
@ eEndRequest
HTTP request processed, all results sent to client.
Definition: cgiapp.hpp:194
@ eExecutable
FCGI forced to exit as its modif. time has changed.
Definition: cgiapp.hpp:196
@ eWatchFile
FCGI forced to exit as its "watch file" has changed.
Definition: cgiapp.hpp:197
@ eExitOnFail
[FastCGI].StopIfFailed set, and the iteration failed
Definition: cgiapp.hpp:198
@ eSuccess
The HTTP request was processed, with zero exit code.
Definition: cgiapp.hpp:190
EDiagSev
Severity level for the posted diagnostics.
Definition: ncbidiag.hpp:650
#define NCBI_PARAM_DECL_EXPORT(expname, type, section, name)
Same as NCBI_PARAM_DECL but with export specifier (e.g.
Definition: ncbi_param.hpp:164
#define NCBI_PARAM_ENUM_DECL_EXPORT(expname, type, section, name)
Same as NCBI_PARAM_ENUM_DECL but with export specifier (e.g.
Definition: ncbi_param.hpp:194
#define NCBI_DEPRECATED
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
Definition: ncbistre.hpp:149
IO_PREFIX::istream CNcbiIstream
Portable alias for istream.
Definition: ncbistre.hpp:146
#define kEmptyStr
Definition: ncbistr.hpp:123
void Reset(void)
Reset thread local storage.
Definition: ncbithr.hpp:217
#define NCBI_SBUILDINFO_DEFAULT()
Definition: version.hpp:119
char * buf
mdb_mode_t mode
Definition: lmdb++.h:38
const struct ncbi::grid::netcache::search::fields::KEY key
Defines the CNcbiApplication and CAppException classes for creating NCBI applications.
Process information in the NCBI Registry, including working with configuration files.
static Format format
Definition: njn_ioutil.cpp:53
std::istream & in(std::istream &in_, double &x_)
"Accept:" header entry.
Definition: cgiapp.hpp:340
This class allows to add build info (date and tag) to application version.
Definition: version_api.hpp:62
else result
Definition: token2.c:20
static CS_CONTEXT * context
Definition: will_convert.c:21
static wxAcceleratorEntry entries[3]
Modified on Sat May 25 14:20:20 2024 by modify_doxy.py rev. 669887