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 103082 2024-09-05 19:04:40Z satskyse $
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_HealthZ, ///< Report health for this CGI as kubernetes expects
331  eAdmin_ReadyZ, ///< Report readyness for this CGI as kubernetes expects
332  eAdmin_LiveZ, ///< Report if this CGI is alive as kubernetes expects
333  eAdmin_Unknown ///< Unrecognized command. Overriden ProcessAdminRequest()
334  ///< can use GetEntry() to fetch command name if necessary.
335  };
336 
337  /// Process admin command passed through ncbi_admin_cmd argument.
338  /// Return true on success, false if the command was not processed
339  /// (in this case the default processing will be used).
340  virtual bool ProcessAdminRequest(EAdminCommand cmd);
341 
342  /// "Accept:" header entry.
343  struct SAcceptEntry {
344  SAcceptEntry(void) : m_Quality(1) {}
345 
347 
348  string m_Type;
349  string m_Subtype;
350  float m_Quality; ///< Quality factor or "1" if not set (or not numeric).
351  string m_MediaRangeParams; ///< Media range parameters
352  TParams m_AcceptParams; ///< Accept parameters
353 
354  bool operator<(const SAcceptEntry& entry) const;
355  };
356 
357  typedef list<SAcceptEntry> TAcceptEntries;
358 
359  /// Parse "Accept:" header, put entries to the list, more specific first.
360  void ParseAcceptHeader(TAcceptEntries& entries) const;
361 
362  /// Create request processor to process the request. If the method returns null,
363  /// the application's ProcessRequest() method is used for the request. Otherwise
364  /// request is passed to the processor.
365  /// @sa CCgiRequestProcessor
366  virtual CCgiRequestProcessor* CreateRequestProcessor(void);
367 
368 protected:
369  /// Set CONN_HTTP_REFERER, print self-URL and referer to log.
370  void ProcessHttpReferer(void);
371 
372  /// @deprecated Use LogRequest(const CCgiContext&) instead.
373  NCBI_DEPRECATED void LogRequest(void) const;
374  /// Write the required values to log (user-agent, self-url, referer etc.)
375  void LogRequest(const CCgiContext& ctx) const;
376 
377  /// Bit flags for CCgiRequest
379 
380  // If FastCGI-capable, and run as a Fast-CGI, then iterate through
381  // the FastCGI loop (doing initialization and running ProcessRequest()
382  // for each HTTP request); then return TRUE.
383  // Return FALSE overwise.
384  // In the "result", return # of requests whose processing has failed
385  // (exception was thrown or ProcessRequest() returned non-zero value)
386  virtual bool x_RunFastCGI(int* result, unsigned int def_iter = 10);
387 
388  string GetFastCGIStandaloneServer(void) const;
389  bool GetFastCGIStatLog(void) const;
390  unsigned int GetFastCGIIterations(unsigned int def_iter) const;
391  bool GetFastCGIComplete_Request_On_Sigterm(void) const;
392  CCgiWatchFile* CreateFastCGIWatchFile(void) const;
393  unsigned int GetFastCGIWatchFileTimeout(bool have_watcher) const;
394  int GetFastCGIWatchFileRestartDelay(void) const;
395  bool GetFastCGIChannelErrors(void) const;
396  bool GetFastCGIHonorExitRequest(void) const;
397  bool GetFastCGIDebug(void) const;
398  bool GetFastCGIStopIfFailed(void) const;
399  unsigned int GetFastCGIMTMaxThreads(void) const;
400 
401  static CTime GetFileModificationTime(const string& filename);
402  // Return true if current memory usage is above the limit.
403  bool CheckMemoryLimit(void);
404  void InitArgs(CArgs& args, CCgiContext& context) const;
405  void AddLBCookie(CCgiCookies& cookies);
406  virtual ICache* GetCacheStorage(void) const;
407  virtual bool IsCachingNeeded(const CCgiRequest& request) const;
408  bool GetResultFromCache(const CCgiRequest& request, CNcbiOstream& os, ICache& cache);
409  void SaveResultToCache(const CCgiRequest& request, CNcbiIstream& is, ICache& cache);
410  void SaveRequest(const string& rid, const CCgiRequest& request, ICache& cache);
411  CCgiRequest* GetSavedRequest(const string& rid, ICache& cache);
412  bool x_ProcessHelpRequest(CCgiRequestProcessor& processor);
413  bool x_ProcessVersionRequest(CCgiRequestProcessor& processor);
414  bool x_ProcessAdminRequest(CCgiRequestProcessor& processor);
415 
417  eSR_None = 0,
418  eSR_Executable = 111,
419  eSR_WatchFile = 112
420  };
421  // Decide if this FastCGI process should be finished prematurely, right now
422  // (the criterion being whether the executable or a special watched file
423  // has changed since the last iteration)
424  // NOTE: The method is not MT-safe.
425  static ERestartReason ShouldRestart(CTime& mtime, CCgiWatchFile* watcher, int delay);
426 
427  // Write message to the application log, call OnEvent()
428  void x_OnEvent(CCgiRequestProcessor* pprocessor, EEvent event, int status);
429  // Backward compatibility
430  void x_OnEvent(EEvent event, int status) { x_OnEvent(x_GetProcessorOrNull(), event, status); }
431 
432  // Create processor and store it in TLS.
433  CCgiRequestProcessor& x_CreateProcessor(void);
434 
437  CAtomicCounter m_Iteration; // (always 0 for plain CGI)
438 
439 private:
440 
441  // Add cookie with load balancer information
442  void x_AddLBCookie();
443 
444  CCgiContext& x_GetContext (void) const;
445  CNcbiResource& x_GetResource(void) const;
446  bool x_IsSetProcessor(void) const;
447  CCgiRequestProcessor& x_GetProcessor(void) const;
448  CCgiRequestProcessor* x_GetProcessorOrNull(void) const;
449 
450  // Check if HEAD request has been served.
451  bool x_DoneHeadRequest(CCgiContext& context) const;
452 
453  unique_ptr<CNcbiResource> m_Resource;
454 
457 
458  unique_ptr<CCookieAffinity> m_Caf; // Cookie affinity service pointer
459  char* m_HostIP; // Cookie affinity host IP buffer
460 
461  // Environment var. value to put to the diag.prefix; [CGI].DiagPrefixEnv
463 
464  /// @sa FASTCGI_ScheduleExit()
465  bool m_ShouldExit = false;
466 
467  // forbidden
470 };
471 
472 
473 /////////////////////////////////////////////////////////////////////////////
474 // CCgiStatistics::
475 //
476 // CGI statistics information
477 //
478 
480 {
481  friend class CCgiApplication;
482  friend class CFastCgiApplicationMT;
483 public:
484  virtual ~CCgiStatistics();
485 
486 protected:
488 
489  // Reset statistics class. Method called only ones for CGI
490  // applications and every iteration if it is FastCGI.
491  virtual void Reset(const CTime& start_time,
492  int result,
493  const std::exception* ex = 0);
494 
495  // Compose message for statistics logging.
496  // This default implementation constructs the message from the fragments
497  // composed with the help of "Compose_Xxx()" methods (see below).
498  // NOTE: It can return empty string (when time cut-off is engaged).
499  virtual string Compose(void);
500 
501  // Log the message
502  virtual void Submit(const string& message);
503 
504 protected:
505  virtual string Compose_ProgramName (void);
506  virtual string Compose_Timing (const CTime& end_time);
507  virtual string Compose_Entries (void);
508  virtual string Compose_Result (void);
509  virtual string Compose_ErrMessage (void);
510 
511 protected:
512  CCgiApplication& m_CgiApp; // Reference on the "mother app"
513  string m_LogDelim; // Log delimiter
514  CTime m_StartTime; // CGI start time
515  int m_Result; // Return code
516  string m_ErrMsg; // Error message
517 };
518 
519 
520 /////////////////////////////////////////////////////////////////////////////
521 // CCgiWatchFile::
522 //
523 // Aux. class for noticing changes to a file
524 //
525 
527 {
528 public:
529  // ignores changes after the first LIMIT bytes
530  CCgiWatchFile(const string& filename, int limit = 1024);
531  bool HasChanged(void);
532 
533 private:
535 
536  string m_Filename;
537  int m_Limit;
538  int m_Count;
540 
541  // returns count of bytes read (up to m_Limit), or -1 if opening failed.
542  int x_Read(char* buf);
543 };
544 
545 
546 /////////////////////////////////////////////////////////////////////////////
547 // CCgiStreamWrapper::
548 //
549 // CGI stream with special processing.
550 //
551 
553 
555 {
556 public:
557  enum EStreamMode {
558  eNormal, // normal output - write all data as-is
559  eBlockWrites, // block all writes after HEAD request
560  eChunkedWrites, // chunked output mode
561  };
562 
564 
566 
567  // Access to writer's methods.
570  void SetCacheStream(CNcbiOstream& stream);
571  void FinishChunkedTransfer(const TTrailer* trailer);
572  void AbortChunkedTransfer(void);
573 
574 private:
576 };
577 
578 
579 /// Base class for request processors.
580 /// @sa CCgiApplication::CreateRequestProcessor()
582 {
583  friend class CCgiApplication;
584 
585 public:
587  virtual ~CCgiRequestProcessor(void);
588 
589  /// Process request provided by the context. By default calls application's ProcessRequest.
590  virtual int ProcessRequest(CCgiContext& context);
591 
592  const CNcbiResource& GetResource(void) const { return m_App.GetResource(); }
593  CNcbiResource& GetResource(void) { return m_App.GetResource(); }
594 
595  virtual bool ValidateSynchronizationToken(void);
596 
597  /// Get self-URL to be used as referer.
598  string GetSelfReferer(void) const;
599 
600 protected:
601  virtual void ProcessHelpRequest(const string& format);
604  virtual int OnException(std::exception& e, CNcbiOstream& os);
605  virtual void OnEvent(CCgiApplication::EEvent event, int status);
606 
607  void SetHTTPStatus(unsigned int status, const string& reason = kEmptyStr);
608  void SetRequestId(const string& rid, bool is_done);
609 
613 
614 private:
615  void x_InitArgs(void) const;
616  // If ProcessAdminRequest is overridden, the base method may still be called.
617  bool ProcessAdminRequest_Base(CCgiApplication::EAdminCommand cmd);
618 
620  shared_ptr<CCgiContext> m_Context;
621  // Parsed cmd.-line args (cmdline + CGI).
622  mutable unique_ptr<CArgs> m_CgiArgs;
623  // Wrappers for cin and cout
624  unique_ptr<CNcbiIstream> m_InputStream;
625  unique_ptr<CNcbiOstream> m_OutputStream;
626  bool m_OutputBroken = false;
627  // Remember if request-start was printed, don't print request-stop
628  // without request-start.
629  bool m_RequestStartPrinted = false;
630  bool m_ErrorStatus = false; // True if HTTP status was set to a value >=400
631  string m_RID;
632  bool m_IsResultReady = true;
633 
634 public:
635  CCgiApplication& GetApp(void) { return m_App; }
636  const CCgiApplication& GetApp(void) const { return m_App; }
637 
638  CCgiContext& GetContext(void) { return *m_Context; }
639  const CCgiContext& GetContext(void) const { return *m_Context; }
640  void SetContext(shared_ptr<CCgiContext> context) { m_Context = context; }
641  bool IsSetContext(void) const { return bool(m_Context); }
642 
643  CArgs& GetArgs(void) { if (!m_CgiArgs) x_InitArgs(); return *m_CgiArgs; }
644  const CArgs& GetArgs(void) const { if (!m_CgiArgs) x_InitArgs(); return *m_CgiArgs; }
645  bool IsSetArgs(void) const { return bool(m_CgiArgs); }
646 
647  CNcbiIstream& GetInputStream(void) { return *m_InputStream; }
648  const CNcbiIstream& GetInputStream(void) const { return *m_InputStream; }
649  void SetInputStream(CNcbiIstream* in) { m_InputStream.reset(in); }
650  bool IsSetInputStream(void) const { return bool(m_InputStream); }
651 
652  CNcbiOstream& GetOutputStream(void) { return *m_OutputStream; }
653  const CNcbiOstream& GetOutputStream(void) const { return *m_OutputStream; }
654  void SetOutputStream(CNcbiOstream* out) { m_OutputStream.reset(out); }
655  bool IsSetOutputStream(void) const { return bool(m_OutputStream); }
656 
657  bool GetOutputBroken(void) const { return m_OutputBroken; }
658  void SetOutputBroken(bool val) { m_OutputBroken = val; }
659 
660  bool GetRequestStartPrinted(void) const { return m_RequestStartPrinted; }
661  void SetRequestStartPrinted(bool val) { m_RequestStartPrinted = val; }
662 
663  bool GetErrorStatus(void) const { return m_ErrorStatus; }
664  void SetErrorStatus(bool val) { m_ErrorStatus = val; }
665 
666  string GetRID(void) const { return m_RID; }
667  void SetRID(const string& val) { m_RID = val; }
668 
669  bool GetResultReady(void) const { return m_IsResultReady; }
670  void SetResultReady(bool val) { m_IsResultReady = val; }
671 };
672 
673 
674 // Aux. class to provide timely reset of "m_Processor" in RunFastCGI()
676 {
677 public:
680 private:
682 };
683 
684 
685 /////////////////////////////////////////////////////////////////////////////
686 // Tracking Environment
687 
689 typedef NCBI_PARAM_TYPE(CGI, DisableTrackingCookie) TCGI_DisableTrackingCookie;
691 typedef NCBI_PARAM_TYPE(CGI, TrackingCookieName) TCGI_TrackingCookieName;
693 typedef NCBI_PARAM_TYPE(CGI, TrackingTagName) TCGI_TrackingTagName;
695 typedef NCBI_PARAM_TYPE(CGI, TrackingCookieDomain) TCGI_TrackingCookieDomain;
697 typedef NCBI_PARAM_TYPE(CGI, TrackingCookiePath) TCGI_TrackingCookiePath;
701  TClientConnIntOk;
705  TClientConnIntSeverity;
706 
708 
709 
710 /* @} */
711 
712 
713 #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:582
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:1312
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:1771
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:1208
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:1751
void SetHTTPStatus(unsigned int status, const string &reason=kEmptyStr)
Definition: cgiapp.cpp:2624
EAdminCommand
Admin commands passed through ncbi_admin_cmd argument.
Definition: cgiapp.hpp:327
~CCgiProcessorGuard(void)
Definition: cgiapp.hpp:679
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:534
const CNcbiResource & GetResource(void) const
Definition: cgiapp.hpp:592
bool GetRequestStartPrinted(void) const
Definition: cgiapp.hpp:660
void SetOutputBroken(bool val)
Definition: cgiapp.hpp:658
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:661
TrackingCookieName
Definition: cgiapp.hpp:690
map< string, string, PNocase > TTrailer
Definition: cgiapp.hpp:565
void SetErrorStatus(bool val)
Definition: cgiapp.hpp:664
string m_Filename
Definition: cgiapp.hpp:536
shared_ptr< CCgiContext > m_Context
Definition: cgiapp.hpp:620
string m_LogDelim
Definition: cgiapp.hpp:513
CCgiStreamWrapperWriter * m_Writer
Definition: cgiapp.hpp:575
bool GetOutputBroken(void) const
Definition: cgiapp.hpp:657
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:653
friend class CCgiRequestProcessor
Definition: cgiapp.hpp:65
CAtomicCounter m_Iteration
Definition: cgiapp.hpp:437
virtual void ProcessVersionRequest(CCgiApplication::EVersionType ver_type)
Definition: cgiapp.cpp:2439
unique_ptr< CNcbiOstream > m_OutputStream
Definition: cgiapp.hpp:625
CTime m_StartTime
Definition: cgiapp.hpp:514
char * m_HostIP
Definition: cgiapp.hpp:459
int x_Read(char *buf)
Definition: cgiapp.cpp:2271
typedef NCBI_PARAM_TYPE(CGI, DisableTrackingCookie) TCGI_DisableTrackingCookie
string m_MediaRangeParams
Media range parameters.
Definition: cgiapp.hpp:351
int m_RequestFlags
Bit flags for CCgiRequest.
Definition: cgiapp.hpp:378
bool HasChanged(void)
Definition: cgiapp.cpp:2291
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:678
CArgs & GetArgs(void)
Definition: cgiapp.hpp:643
void SetRID(const string &val)
Definition: cgiapp.hpp:667
virtual bool ProcessAdminRequest(CCgiApplication::EAdminCommand cmd)
Definition: cgiapp.cpp:2495
bool IsSetArgs(void) const
Definition: cgiapp.hpp:645
CCgiApplication(const CCgiApplication &)
CCgiApplication::SAcceptEntry TAcceptEntry
Definition: cgiapp.hpp:611
void SetInputStream(CNcbiIstream *in)
Definition: cgiapp.hpp:649
unique_ptr< CNcbiResource > m_Resource
Definition: cgiapp.hpp:453
CCgiWatchFile(const string &filename, int limit=1024)
Definition: cgiapp.cpp:2282
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:1252
CNcbiOstream & GetOutputStream(void)
Definition: cgiapp.hpp:652
virtual void OnEvent(CCgiApplication::EEvent event, int status)
Definition: cgiapp.cpp:2618
virtual void ProcessHelpRequest(const string &format)
Definition: cgiapp.cpp:2329
float m_Quality
Quality factor or "1" if not set (or not numeric).
Definition: cgiapp.hpp:350
bool GetErrorStatus(void) const
Definition: cgiapp.hpp:663
map< string, string > TParams
Definition: cgiapp.hpp:346
friend void s_ScheduleFastCGIExit(void)
CTls< CCgiRequestProcessor > * m_Proc
Definition: cgiapp.hpp:681
CCgiApplication & m_App
Definition: cgiapp.hpp:619
EStreamMode GetWriterMode(void)
Definition: cgiapp.cpp:421
void x_OnEvent(EEvent event, int status)
Definition: cgiapp.hpp:430
DisableTrackingCookie
Definition: cgiapp.hpp:688
const CCgiApplication & GetApp(void) const
Definition: cgiapp.hpp:636
virtual bool ProcessAdminRequest(EAdminCommand cmd)
Process admin command passed through ncbi_admin_cmd argument.
Definition: cgiapp.cpp:1869
friend class CCgiApplication
Definition: cgiapp.hpp:583
void SetRequestId(const string &rid, bool is_done)
Definition: cgiapp.cpp:2641
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:1684
CNcbiResource & GetResource(void)
Definition: cgiapp.hpp:593
unique_ptr< CCookieAffinity > m_Caf
Definition: cgiapp.hpp:458
CCgiApplication::TAcceptEntries TAcceptEntries
Definition: cgiapp.hpp:610
virtual int OnException(std::exception &e, CNcbiOstream &os)
Definition: cgiapp.cpp:2541
void SetWriterMode(EStreamMode mode)
Definition: cgiapp.cpp:427
bool IsSetOutputStream(void) const
Definition: cgiapp.hpp:655
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:692
virtual bool ValidateSynchronizationToken(void)
Definition: cgiapp.cpp:2515
CCgiApplication & GetApp(void)
Definition: cgiapp.hpp:635
NCBI_XCGI_EXPORT
Definition: cgiapp.hpp:688
string GetRID(void) const
Definition: cgiapp.hpp:666
TDiagFactoryMap m_DiagFactories
Definition: cgiapp.hpp:456
TrackingCookiePath
Definition: cgiapp.hpp:696
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:1882
const CArgs & GetArgs(void) const
Definition: cgiapp.hpp:644
const CCgiContext & GetContext(void) const
Definition: cgiapp.hpp:639
friend class CCgiStatistics
Definition: cgiapp.hpp:64
string m_DiagPrefixEnv
Definition: cgiapp.hpp:462
void SetRequestId(const string &rid, bool is_done)
Definition: cgiapp.cpp:1462
virtual void ProcessHelpRequest(const string &format)
Process help request: set content type, print usage informations etc.
Definition: cgiapp.cpp:1769
bool IsSetInputStream(void) const
Definition: cgiapp.hpp:650
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:640
CCgiApplication & m_CgiApp
Definition: cgiapp.hpp:512
string m_ErrMsg
Definition: cgiapp.hpp:516
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:654
const CNcbiIstream & GetInputStream(void) const
Definition: cgiapp.hpp:648
bool IsSetContext(void) const
Definition: cgiapp.hpp:641
virtual void ProcessVersionRequest(EVersionType ver_type)
Process version request: set content type, print version informations etc.
Definition: cgiapp.cpp:1826
CCgiContext & GetContext(void)
Definition: cgiapp.hpp:638
void SetResultReady(bool val)
Definition: cgiapp.hpp:670
unsigned int GetFCgiIteration(void) const
Get the # of currently processed HTTP request.
Definition: cgiapp.hpp:91
list< SAcceptEntry > TAcceptEntries
Definition: cgiapp.hpp:357
CRef< CTls< CCgiRequestProcessor > > m_Processor
Definition: cgiapp.hpp:436
Client_Connection_Interruption_Okay
Definition: cgiapp.hpp:699
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:1733
map< string, CDiagFactory * > TDiagFactoryMap
Definition: cgiapp.hpp:455
unique_ptr< CArgs > m_CgiArgs
Definition: cgiapp.hpp:622
bool m_CaughtSigterm
Definition: cgiapp.hpp:435
CCgiStreamWrapper(CNcbiOstream &out)
Definition: cgiapp.cpp:414
Client_Connection_Interruption_Severity
Definition: cgiapp.hpp:703
CNcbiIstream & GetInputStream(void)
Definition: cgiapp.hpp:647
bool GetResultReady(void) const
Definition: cgiapp.hpp:669
CCgiApplication & operator=(const CCgiApplication &)
TParams m_AcceptParams
Accept parameters.
Definition: cgiapp.hpp:352
void FinishChunkedTransfer(const TTrailer *trailer)
Definition: cgiapp.cpp:440
bool
Definition: cgiapp.hpp:688
TrackingCookieDomain
Definition: cgiapp.hpp:694
unique_ptr< CNcbiIstream > m_InputStream
Definition: cgiapp.hpp:624
CGI
Definition: cgiapp.hpp:688
@ eAdmin_HealthZ
Report health for this CGI as kubernetes expects.
Definition: cgiapp.hpp:330
@ 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
@ eAdmin_LiveZ
Report if this CGI is alive as kubernetes expects.
Definition: cgiapp.hpp:332
@ eAdmin_ReadyZ
Report readyness for this CGI as kubernetes expects.
Definition: cgiapp.hpp:331
@ 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:343
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 Fri Sep 20 14:57:21 2024 by modify_doxy.py rev. 669887