CRef<CGC_Assembly> CGenomicCollectionsService::GetAssembly(const string& acc_,
                                            int level, 
                                            int asmAttrFlags, 
                                            int chrAttrFlags, 
                                            int scafAttrFlags, 
                                            int compAttrFlags)
{
    string acc = NStr::TruncateSpaces(acc_);
    ValidateAsmAccession(acc);

    CGCClient_GetAssemblyRequest req;
    CGCClientResponse reply;

    req.SetAccession(acc);
    req.SetLevel(level);
    req.SetAssm_flags(asmAttrFlags);
    req.SetChrom_flags(chrAttrFlags);
    req.SetScaf_flags(scafAttrFlags);
    req.SetComponent_flags(compAttrFlags);

    LogRequest(req);

    try {
        return AskGet_assembly(req, &reply);
    } catch (CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription());
        }
        throw;
    }
}
CRef<CGCClient_AssembliesForSequences> CGenomicCollectionsService::FindAssembliesBySequences(const list<string>& sequence_acc, int filter, CGCClient_GetAssemblyBySequenceRequest::ESort sort, bool top_only)

{
    CGCClient_GetAssemblyBySequenceRequest req;
    CGCClientResponse reply;

    for(auto acc : sequence_acc)
        if(acc.length() > 30) {
            NCBI_THROW(CException, eUnknown, "Accession is longer than 30 characters: " + acc);
        }

    req.SetSequence_acc().assign(sequence_acc.begin(), sequence_acc.end());
    req.SetFilter(filter);
    req.SetSort(sort);
    req.SetTop_assembly_only(top_only ? 1 : 0);

    LogRequest(req);

    try {
        CRef<CGCClient_AssembliesForSequences> assm = AskGet_assembly_by_sequence(req, &reply);

        return assm;
    } catch (const CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_REPORT_EXCEPTION(reply.GetSrvr_error().GetDescription(), ex);
        }
        throw;
    }
    return CRef<CGCClient_AssembliesForSequences>();
}
CRef<CGCClient_AssemblySequenceInfo> CGenomicCollectionsService::FindBestAssembly(const list<string>& seq_id, int filter_type, int sort_type)
{
    CGCClient_FindBestAssemblyRequest  req;
    CGCClientResponse reply;

    req.SetSeq_id_acc().assign(seq_id.begin(), seq_id.end());
    req.SetFilter(filter_type);
    req.SetSort(sort_type);
    req.SetAssembly_return_limit(1);

    LogRequest(req);

    try {
        CRef<CGCClient_AssembliesForSequences> assm = AskGet_best_assembly(req, &reply);

        return assm->CanGetAssemblies() && !assm->GetAssemblies().empty() ?
               CRef<CGCClient_AssemblySequenceInfo>(assm->SetAssemblies().front()) :
               CRef<CGCClient_AssemblySequenceInfo>();
    } catch (const CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_REPORT_EXCEPTION(reply.GetSrvr_error().GetDescription().c_str(), ex);
        }
        throw;
    }
}
CRef<CGC_Assembly> CGenomicCollectionsService::GetAssembly(int releaseId, 
                                            int level, 
                                            int asmAttrFlags, 
                                            int chrAttrFlags, 
                                            int scafAttrFlags, 
                                            int compAttrFlags)
{
    CGCClient_GetAssemblyRequest req;
    CGCClientResponse reply;

    req.SetRelease_id(releaseId);
    req.SetLevel(level);
    req.SetAssm_flags(asmAttrFlags);
    req.SetChrom_flags(chrAttrFlags);
    req.SetScaf_flags(scafAttrFlags);
    req.SetComponent_flags(compAttrFlags);

    LogRequest(req);

    try {
        return AskGet_assembly(req, &reply);
    } catch (CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription());
        }
        throw;
    }
}
string CGenomicCollectionsService::ValidateChrType(const string& chrType, const string& chrLoc)
{
    CGCClient_ValidateChrTypeLocRequest req;
    CGCClientResponse reply;
    
    req.SetType(chrType);
    req.SetLocation(chrLoc);

    LogRequest(req);

    try {
        return AskGet_chrtype_valid(req, &reply);
    } catch (CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription());
        }
        throw;
    }
}
CRef<CGC_Assembly> CGenomicCollectionsService::GetAssembly(int releaseId, const string& mode)
{
    CGCClient_GetAssemblyBlobRequest req;
    CGCClientResponse reply;

    req.SetRelease_id(releaseId);
    req.SetMode(mode);

    LogRequest(req);

    try {
        return CCachedAssembly(AskGet_assembly_blob(req, &reply)).Assembly();
    } catch (CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription());
        }
        throw;
    }
}
CRef<CGCClient_EquivalentAssemblies> CGenomicCollectionsService::GetEquivalentAssemblies(const string& acc, int equivalency)
{
    CGCClient_GetEquivalentAssembliesRequest req;
    CGCClientResponse reply;

    req.SetAccession(acc);
    req.SetEquivalency(equivalency);

    LogRequest(req);

    try {
        CRef<CGCClient_EquivalentAssemblies> assm = AskGet_equivalent_assemblies(req, &reply);

        return assm;
    } catch (const CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_REPORT_EXCEPTION(reply.GetSrvr_error().GetDescription(), ex);
        }
        throw;
    }
}
QTSS_Error PostProcess(QTSS_StandardRTSP_Params* inParams)
{
	static UInt32 sZero = 0;

	UInt32* theStatus = NULL;
	UInt32 theLen = 0;
	QTSS_Error theErr = QTSS_GetValuePtr(inParams->inRTSPRequest, qtssRTSPReqRealStatusCode, 0, (void**)&theStatus, &theLen);
	if (theErr != QTSS_NoErr)
		return theErr;

	QTSS_CliSesClosingReason theReason = qtssCliSesCloseClientTeardown;

	if ((*theStatus == 401) || (*theStatus == 403))
	{
		LogRequest(inParams->inClientSession, NULL, &theReason);
		(void)QTSS_SetValue(inParams->inClientSession, sLoggedAuthorizationAttrID, 0, theStatus, sizeof(*theStatus));
	}
	else
		(void)QTSS_SetValue(inParams->inClientSession, sLoggedAuthorizationAttrID, 0, &sZero, sizeof(sZero));

	return theErr;
}
CRef<CGC_Assembly> CGenomicCollectionsService::GetAssembly(const string& acc_, const string& mode)
{
    string acc = NStr::TruncateSpaces(acc_);
    ValidateAsmAccession(acc);

    CGCClient_GetAssemblyBlobRequest req;
    CGCClientResponse reply;

    req.SetAccession(acc);
    req.SetMode(mode);

    LogRequest(req);

    try {
        return CCachedAssembly(AskGet_assembly_blob(req, &reply)).Assembly();
    } catch (CException& ex) {
        if(reply.IsSrvr_error()) {
            NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription());
        }
        throw;
    }
}
Exemple #10
0
UINT ServerThreadProc(LPVOID pParam)
{
	CSocketAddress saClient;
	CMyHttpBlockSocket sConnect;
	CListBox* pList=(CListBox*)pParam;
	//缓存区
	char* buffer=new char[SERVERMAXBUF];
	char headers[500], 
		 request1[MAXLINELENGTH],  
		 request2[MAXLINELENGTH];
	//连接错误返回到浏览的信息
	char hdrErr[]=
		"HTTP/1.0 404 对象没有找到\r\n"
		"Server: MySocket Server\r\n"
		"Content-Type: text/html\r\n"
		"Accept-Ranges: bytes\r\n"
		"Content-Length: 66\r\n\r\n"
		"<html><h1><body>HTTP/1.0 404 对象没有找到</h1></body></html>\r\n";
	//连接正确时返回的信息
	char hdrFmt[]=
		"HTTP/1.0 200 OK\r\n"
		"Server: MySocket Server\r\n"
		"Date: %s\r\n"
		"Content-Type: text/html\r\n"
		"Accept-Ranges: bytes\r\n"
		"Content-Length: %d\r\n";
	//默认的页面--default HTML page
	char CustomHtml[]=
		"<html>\r\n"
		"<head>\r\n"
		"<title></title>\r\n"
		"</head>\r\n"
		"<body>\r\n"
		"<p align=\"center\">欢迎访问我的主页</p>\r\n"
		"<h3 align=\"center\"><a href=\"Default.htm\">快乐天地</a></h3>\r\n"
		"<p>结束</p>\r\n"
		"<p> </p>\r\n"
		"</body></html>\r\n\r\n";
	
	CString strGmtNow=
		CTime::GetCurrentTime().FormatGmt("%a, %d %b %Y %H:%M:%S GMT");
	int nBytesSent=0;
	CFile* pFile=NULL;
	char* pToken1;
	char* pToken2;
    char* pData = NULL;
    char StringSeparates[64] = { 0 };
    int nStringSeparates = 0;
	try 
	{
		//开始侦听连接请求
		if(!g_sListen.Accept(sConnect, saClient)) 
		{
			//在应用程序关闭时的处理
			g_bListening=FALSE;
			delete [] buffer;
			return 0;
		}
		//连接数增加一个
		g_nConnection++;
		//开始另一个服务器线程
		AfxBeginThread(ServerThreadProc, pParam, THREAD_PRIORITY_NORMAL);
		//从客户端(浏览器)读取请求
		sConnect.ReadHttpHeaderLine(request1, MAXLINELENGTH, 10);
		//记录请求
		LogRequest(pParam, request1, saClient);
		//解析请求并作相应的处理
		if(Parse(request1, &pToken1, &pToken2))
		{
			//浏览器GET方式
			if(!stricmp(pToken1, "GET")) 
			{
				do 
				{	
					//读取请求的剩余部分
					sConnect.ReadHttpHeaderLine(request2, MAXLINELENGTH, 10);
				}
				while(strcmp(request2, "\r\n"));
				if(!stricmp(pToken2, "/custom"))// || !stricmp(pToken2, "/"))
				{
					//发送默认的页面--default HTML page
					wsprintf(headers, hdrFmt, (const char*) strGmtNow, strlen(CustomHtml));
					strcat(headers, "\r\n");
					sConnect.Write(headers, strlen(headers), 10);
					sConnect.Write(CustomHtml, strlen(CustomHtml), 10);
				}
				else if(strchr(pToken2, '?')) 
				{
					//CGI请求
					//该HTTP服务器还不能对CGI请求作出响应
					//也不能调用相应的ISAPI的DLL(动态连接库)
				}
				else
				{
					//文件处理
					//注意对服务器目录的设定
					//获得文件在服务器上的路径
					if((pFile=OpenFile(pToken2))!=NULL) 
					{
						//文件打开
						CFileStatus fileStatus;
						pFile->GetStatus(fileStatus);
						CString strGmtMod=fileStatus.m_mtime.FormatGmt("%a, %d %b %Y %H:%M:%S GMT");
						char hdrModified[50];
						wsprintf(hdrModified, "Last-Modified: %s\r\n\r\n", (const char*) strGmtMod);
						DWORD dwLength=pFile->GetLength();
						wsprintf(headers, hdrFmt,  (const char*) strGmtNow, dwLength);
						strcat(headers, hdrModified);
						nBytesSent=sConnect.Write(headers, strlen(headers), 10);
						//传送的文件应该是在某一个时间之后被修改过的
						//因此文件的时间应该是小于该设定时间
						nBytesSent=0;
						DWORD dwBytesRead=0;
						UINT uBytesToRead;
						//将文件以5k的大小为单位发送,避免内存分配错误
						while(dwBytesRead < dwLength) 
						{
							uBytesToRead=min(SERVERMAXBUF, dwLength-dwBytesRead);
							VERIFY(pFile->Read(buffer, uBytesToRead)==uBytesToRead);
							nBytesSent+=sConnect.Write(buffer, uBytesToRead, 10);
							dwBytesRead+=uBytesToRead;
						}
                        pFile->Close();
					}
					else
					{
						//向浏览器发送“出错信息”
						nBytesSent=sConnect.Write(hdrErr, strlen(hdrErr), 10);
					}
				}
			}
			else if(!stricmp(pToken1, "POST"))
			{
                int nDataSize = 0;
				//浏览器POST方式
				do 
				{
					//读取请求的剩余部分
					sConnect.ReadHttpHeaderLine(request2, MAXLINELENGTH, 10);
                    char *p = strstr(request2, "Content-Length: ");
                    if (NULL != p)
                    {
                        char *Size = p + 16;
                        nDataSize = atoi(Size);
                    }
                    char *psp = strstr(request2, "boundary");
                    if (NULL != psp)
                    {
                        psp+=9;
                        for (int i = 0; '\r' != *psp && i < 64; ++i, ++psp)
                        {
                            StringSeparates[i] = *psp;
                            nStringSeparates++;
                        }

                        
                    }
				}
				while(strcmp(request2, "\r\n"));

//                 sConnect.ReadHttpHeaderLine(request2, MAXLINELENGTH, 10);
//                 sConnect.ReadHttpHeaderLine(request2, MAXLINELENGTH, 10);
//                 sConnect.ReadHttpHeaderLine(request2, MAXLINELENGTH, 10);
                pData = new char[nDataSize];
                sConnect.ReadHttpResponse(pData, nDataSize, 10);

				LogRequest(pParam, request2, saClient);
				//向浏览器发送“出错信息”
				//nBytesSent=sConnect.Write(hdrErr, strlen(hdrErr), 10);
                nBytesSent = sConnect.Write(hdrFmt, strlen(hdrFmt), 10);
                // 
                CHttpDataAnalyse ana(pData, nDataSize);

                ana.SetStringSeparates(StringSeparates, nStringSeparates);
                if (ana.Analyse())
                {
                    TRACE("ok");
                }
			}
			else 
			{
				//其它的请求方式
			}
		}
		else 
		{
			//错误的请求
		}
		//关闭套接字
		sConnect.Close();

        // 
	}
	catch(CMyBlockSocketException* pe)
	{
		//错误处理
		LogBlockingSocketException(pParam, "服务器:", pe);
		pe->Delete();
	}

	delete [] buffer;
	if(pFile) delete pFile;
    if (NULL != pData) 
    {
        delete pData;
        pData = NULL;
    }
    return 0;
}
Exemple #11
0
int CCgiApplication::Run(void)
{
    // Value to return from this method Run()
    int result;

    // Try to run as a Fast-CGI loop
    if ( x_RunFastCGI(&result) ) {
        return result;
    }

    /// Run as a plain CGI application

    // Make sure to restore old diagnostic state after the Run()
    CDiagRestorer diag_restorer;

#if defined(NCBI_OS_UNIX)
    // Disable SIGPIPE if not allowed.
    if ( !TParamAllowSigpipe::GetDefault() ) {
        signal(SIGPIPE, SIG_IGN);
        struct sigaction sigterm,  sigtermold;
        memset(&sigterm, 0, sizeof(sigterm));
        sigterm.sa_handler = SigTermHandler;
        sigterm.sa_flags = SA_RESETHAND;
        if (sigaction(SIGTERM, &sigterm, &sigtermold) == 0
            &&  sigtermold.sa_handler != SIG_DFL) {
            sigaction(SIGTERM, &sigtermold, 0);
        }
    }

    // Compose diagnostics prefix
    PushDiagPostPrefix(NStr::IntToString(getpid()).c_str());
#endif
    PushDiagPostPrefix(GetEnvironment().Get(m_DiagPrefixEnv).c_str());

    // Timing
    CTime start_time(CTime::eCurrent);

    // Logging for statistics
    bool is_stat_log = GetConfig().GetBool("CGI", "StatLog", false,
                                           0, CNcbiRegistry::eReturn);
    bool skip_stat_log = false;
    auto_ptr<CCgiStatistics> stat(is_stat_log ? CreateStat() : 0);

    CNcbiOstream* orig_stream = NULL;
    //int orig_fd = -1;
    CNcbiStrstream result_copy;
    auto_ptr<CNcbiOstream> new_stream;

    try {
        _TRACE("(CGI) CCgiApplication::Run: calling ProcessRequest");
        GetDiagContext().SetAppState(eDiagAppState_RequestBegin);

        m_Context.reset( CreateContext() );
        _ASSERT(m_Context.get());
        m_Context->CheckStatus();

        ConfigureDiagnostics(*m_Context);
        x_AddLBCookie();
        try {
            // Print request start message
            x_OnEvent(eStartRequest, 0);

            VerifyCgiContext(*m_Context);
            ProcessHttpReferer();
            LogRequest();

            try {
                m_Cache.reset( GetCacheStorage() );
            } catch( exception& ex ) {
                ERR_POST_X(1, "Couldn't create cache : " << ex.what());
            }
            bool skip_process_request = false;
            bool caching_needed = IsCachingNeeded(m_Context->GetRequest());
            if (m_Cache.get() && caching_needed) {
                skip_process_request = GetResultFromCache(m_Context->GetRequest(),
                                                           m_Context->GetResponse().out());
            }
            if (!skip_process_request) {
                if( m_Cache.get() ) {
                    list<CNcbiOstream*> slist;
                    orig_stream = m_Context->GetResponse().GetOutput();
                    slist.push_back(orig_stream);
                    slist.push_back(&result_copy);
                    new_stream.reset(new CWStream(new CMultiWriter(slist), 0,0,
                                                  CRWStreambuf::fOwnWriter));
                    m_Context->GetResponse().SetOutput(new_stream.get());
                }
                GetDiagContext().SetAppState(eDiagAppState_Request);
                result = CCgiContext::ProcessCORSRequest(
                    m_Context->GetRequest(), m_Context->GetResponse()) ?
                    0 : ProcessRequest(*m_Context);
                GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
                m_Context->GetResponse().Finalize();
                if (result != 0) {
                    SetHTTPStatus(500);
                    m_ErrorStatus = true;
                } else {
                    if (m_Cache.get()) {
                        m_Context->GetResponse().Flush();
                        if (m_IsResultReady) {
                            if(caching_needed)
                                SaveResultToCache(m_Context->GetRequest(), result_copy);
                            else {
                                auto_ptr<CCgiRequest> request(GetSavedRequest(m_RID));
                                if (request.get()) 
                                    SaveResultToCache(*request, result_copy);
                            }
                        } else if (caching_needed) {
                            SaveRequest(m_RID, m_Context->GetRequest());
                        }
                    }
                }
            }
        }
        catch (CCgiException& e) {
            if ( x_DoneHeadRequest() ) {
                // Ignore errors after HEAD request has been finished.
                GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
            }
            else {
                if ( e.GetStatusCode() <  CCgiException::e200_Ok  ||
                     e.GetStatusCode() >= CCgiException::e400_BadRequest ) {
                    throw;
                }
                GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
                // If for some reason exception with status 2xx was thrown,
                // set the result to 0, update HTTP status and continue.
                m_Context->GetResponse().SetStatus(e.GetStatusCode(),
                                                   e.GetStatusMessage());
            }
            result = 0;
        }

#ifdef NCBI_OS_MSWIN
        // Logging - on MSWin this must be done before flushing the output.
        if ( is_stat_log  &&  !skip_stat_log ) {
            stat->Reset(start_time, result);
            stat->Submit(stat->Compose());
        }
        is_stat_log = false;
#endif

        _TRACE("CCgiApplication::Run: flushing");
        m_Context->GetResponse().Flush();
        _TRACE("CCgiApplication::Run: return " << result);
        x_OnEvent(result == 0 ? eSuccess : eError, result);
        x_OnEvent(eExit, result);
    }
    catch (exception& e) {
        GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
        if ( x_DoneHeadRequest() ) {
            // Ignore errors after HEAD request has been finished.
            result = 0;
            x_OnEvent(eSuccess, result);
        }
        else {
            // Call the exception handler and set the CGI exit code
            result = OnException(e, NcbiCout);
            x_OnEvent(eException, result);

            // Logging
            {{
                string msg = "(CGI) CCgiApplication::ProcessRequest() failed: ";
                msg += e.what();

                if ( is_stat_log ) {
                    stat->Reset(start_time, result, &e);
                    msg = stat->Compose();
                    stat->Submit(msg);
                    skip_stat_log = true; // Don't print the same message again
                }
            }}

            // Exception reporting. Use different severity for broken connection.
            ios_base::failure* fex = dynamic_cast<ios_base::failure*>(&e);
            CNcbiOstream* os = m_Context.get() ? m_Context->GetResponse().GetOutput() : NULL;
            if ((fex  &&  os  &&  !os->good())  ||  m_OutputBroken) {
                if ( !TClientConnIntOk::GetDefault() ) {
                    ERR_POST_X(13, Severity(TClientConnIntSeverity::GetDefault()) <<
                        "Connection interrupted");
                }
            }
            else {
                NCBI_REPORT_EXCEPTION_X(13, "(CGI) CCgiApplication::Run", e);
            }
        }
    }

#ifndef NCBI_OS_MSWIN
    // Logging
    if ( is_stat_log  &&  !skip_stat_log ) {
        stat->Reset(start_time, result);
        stat->Submit(stat->Compose());
    }
#endif

    x_OnEvent(eEndRequest, 120);
    x_OnEvent(eExit, result);

    if (m_Context.get()) {
        m_Context->GetResponse().SetOutput(NULL);
    }
    return result;
}
Exemple #12
0
// Main execution loop.  This loop executes correctly when run both as a
// standard Cgi app and when running as a FastCgi process.  This loop is
// single threaded.  Multiple FastCgi processes are started to handle
// concurrent incoming requests.
int main ()
{
#ifdef _WIN32
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    #ifdef _DEBUG
    // to debug memory leaks, set a breakpoint here and set iBlock
    // to the block allocation you want to break on
    long iBlock = -1;
    _CrtSetBreakAlloc(iBlock);
    #endif
#endif

    bool bFirstTime = true;
    int nRequests = 1;
    INT32 dbgPause = 0;

    CgiPostParser postParser;

    MG_TRY()

        // If Web Tier generates an exception which is not caught
        // by the HTTP handler execute, we should exit to reduce
        // the likelihood of a hung agent lying around.

        if (bFirstTime)
        {
            bFirstTime = false;
#ifdef _WIN32
            // Set stdin and stdout to binary mode
            _setmode(0, _O_BINARY);
            _setmode(1, _O_BINARY);
#else
            //TODO: Does this need to be done under Linux?
#endif
            //Debugging code
            //EchoTest();
            //break;

            Initialize();
#ifdef _DEBUG
            MgConfiguration* cfg = MgConfiguration::GetInstance();
            cfg->GetIntValue(MgConfigProperties::AgentPropertiesSection, MgConfigProperties::AgentDebugPause, dbgPause, MgConfigProperties::DefaultAgentDebugPause);
#endif

            DumpMessage("Initialized process %d",getpid());
        }

        DumpMessage("Process %d servicing request #%d",getpid(), nRequests);

        // Construct self Url.  It is embedded into the output stream
        // of some requests (like GetMap).  Use a fully qualified URL.
        char* serverName = getenv(MapAgentStrings::ServerName);
        char* serverPort = getenv(MapAgentStrings::ServerPort);
        char* scriptName = getenv(MapAgentStrings::ScriptName);
        char* remoteAddr = getenv(MapAgentStrings::RemoteAddr);
        char* httpClientIp = getenv(MapAgentStrings::HttpClientIp);
        char* httpXFF = getenv(MapAgentStrings::HttpXForwardedFor);
        char* secure = getenv(MapAgentStrings::Secure);
        string url = secure != NULL && (!_stricmp(secure, "on") || !_stricmp(secure, "true")) ? MapAgentStrings::Https : MapAgentStrings::Http;  // NOXLATE
        if (NULL != serverName && NULL != serverPort && NULL != scriptName)
        {
            url.append(serverName);
            url += ':';
            url.append(serverPort);
            url.append(scriptName);
        }
        STRING wUrl = MgUtil::MultiByteToWideChar(url);
        Ptr<MgHttpRequest> request = new MgHttpRequest(wUrl);
        Ptr<MgHttpRequestParam> params = request->GetRequestParam();

        // Temporarily moved here to allow debugging post.
#ifdef _DEBUG
            if(dbgPause > 0)
            {
                DumpMessage("Delaying request %d seconds", dbgPause);
#ifdef _WIN32
                Sleep(dbgPause * 1000L);
#else
                struct timespec delay = { (time_t)dbgPause, 0 };
                nanosleep(&delay, NULL);
#endif
            }
#endif

            // Parse inputs GET/POST
        char* query = getenv(MapAgentStrings::QueryString);
        char* requestMethod = getenv(MapAgentStrings::RequestMethod);
        if (NULL != requestMethod && NULL != strstr(requestMethod, "POST"))
        {
            // Must be a POST request
            postParser.Parse(params);
        }
        else if (NULL != query && strlen(query) > 0)
        {
            DumpMessage2("Query string present");
            DumpMessage2(query);

            // If we have a QUERY_STRING then we are a GET request
            MapAgentGetParser::Parse(query, params);
        }

        // check for CLIENTIP, if it's not there (and it shouldn't be),
        // add it in using httpClientIp. httpXFF or remoteAddr
        STRING clientIp = L"";
        if (!params->ContainsParameter(L"CLIENTIP")) // NOXLATE
        {
            if (NULL != httpClientIp && strlen(httpClientIp) > 0
                && _stricmp(httpClientIp, MapAgentStrings::Unknown) != 0)
            {
                clientIp = MgUtil::MultiByteToWideChar(httpClientIp);
                params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE
            }
            else if (NULL != httpXFF && strlen(httpXFF) > 0
                && _stricmp(httpXFF, MapAgentStrings::Unknown) != 0)
            {
                clientIp = MgUtil::MultiByteToWideChar(httpXFF);
                params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE
            }
            else if (NULL != remoteAddr && strlen(remoteAddr) > 0)
            {
                clientIp = MgUtil::MultiByteToWideChar(remoteAddr);
                params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE
            }
        }

        // Check for HTTP Basic Auth header
        char* auth = getenv(MapAgentStrings::HttpAuth);
        bool gotAuth = ParseAuth(auth, params);

        if (!gotAuth)
        {
            // And check for a REMOTE_USER remapped header
            auth = getenv(MapAgentStrings::HttpRemoteUser);
            gotAuth = ParseAuth(auth, params);
        }

        // Log request information
        string postData = "";
        if (requestMethod && _stricmp(requestMethod, "POST") == 0)  // NOXLATE
        {
            // Get the post xml data
            postData = params->GetXmlPostData();
        }

        STRING client = params->GetParameterValue(MgHttpResourceStrings::reqClientAgent);
        string strRequestMethod= std::string(requestMethod);
        string strQuery = std::string(query);
        LogRequest(client, clientIp, url, strRequestMethod, postData, strQuery);

        Ptr<MgPropertyCollection> paramList = params->GetParameters()->GetPropertyCollection();
        if (paramList != NULL)
        {
            //Check to be sure that we have some kind of credentials before continuing.  Either
            //username/password or sessionid.
            bool bValid = paramList->Contains(MgHttpResourceStrings::reqSession);
            // Strike two: no session? how about a username?
            if (!bValid)
                bValid = paramList->Contains(MgHttpResourceStrings::reqUsername);
            // Strike three: no username either? How about if it's an XML POST
            if (!bValid)
                bValid = params->GetXmlPostData().length() != 0;

            // Certain operations do not require authentication
            STRING operation = params->GetParameterValue(L"OPERATION");
            if((_wcsicmp(operation.c_str(), L"GETSITESTATUS") == 0))
            {
                bValid = true;
            }

            if (!bValid)
            {
                // Invalid authentication information is not fatal, we should continue.
                CgiResponseHandler::RequestAuth();

                // clean up any temporary files we created
                MapAgentCommon::DeleteTempFiles(params);

                return 0;
            }

            Ptr<MgHttpResponse> response = request->Execute();

            // NOTE: temporary files are deleted when we execute the request

            CgiResponseHandler::SendResponse(response);
        }

    MG_CATCH(L"FastCgiAgent.main");

    if (mgException != NULL)
    {
        CgiResponseHandler::SendError(mgException);
    }

    DumpMessage("Process %d serviced request #%d",getpid(), nRequests++);

    MgUninitializeWebTier();

    DumpMessage("Exiting process %d",getpid());

    return 0;
}
QTSS_Error ClientSessionClosing(QTSS_ClientSessionClosing_Params* inParams)
{
	return LogRequest(inParams->inClientSession, NULL, &inParams->inReason);
}