/**
* Downloads the save file from CloudyWeb.
*
* @param Filename               Filename of the save game file.
* @param PlayerControllerId     Player controller ID of the player who requested the file.
*
* @return Returns true if the file download was successful. Else, returns false.
*
*/
bool CloudyWebConnectorImpl::DownloadFile(FString Filename, int32 PlayerControllerId)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    errno_t err;
    std::string SaveFileURLCString;

    if (GetGameId() == -1 || GetUsername(PlayerControllerId).Equals("") || 
        PlayerControllerId < 0 || SaveFileUrls.Num() <= PlayerControllerId)
    {
        UE_LOG(CloudyWebConnectorLog, Error, TEXT("The game ID, username, or player controller ID is invalid"));
        return false;
    }
    
    // Use the game id and username of the player to GET the save file URL from CloudyWeb
    // Then populate SaveFileUrls (TArray)
    GetSaveFileUrl(GetGameId(), GetUsername(PlayerControllerId), PlayerControllerId);

    // Read the URL from the SaveFileUrls TArray to download the file and write to disk
    FString* SaveFileUrlsData = SaveFileUrls.GetData();

    if (!SaveFileUrlsData[PlayerControllerId].Equals(""))
    {
        UE_LOG(CloudyWebConnectorLog, Log, TEXT("File URL obtained! Writing to disk."));
        
        SaveFileURLCString = TCHAR_TO_UTF8(*SaveFileUrlsData[PlayerControllerId]);
        
        // Filepath of .sav file
        FString Filepath = FPaths::GameDir();
        Filepath += "Saved/SaveGames/" + Filename + "-" +
            FString::FromInt(PlayerControllerId) + ".sav";
        std::string filePath(TCHAR_TO_UTF8(*Filepath));
        
        curl = curl_easy_init();
        if (curl) {
            if ((err = fopen_s(&fp, filePath.c_str(), "wb")) == 0)
            {
                curl_easy_setopt(curl, CURLOPT_URL, SaveFileURLCString.c_str());
                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
                res = curl_easy_perform(curl);
                curl_easy_cleanup(curl);
                fclose(fp);
            }
            else
            {
                UE_LOG(CloudyWebConnectorLog, Error, TEXT("Could not create save file!"));
            }
        }
        return true;
    }
    else
    {
        UE_LOG(CloudyWebConnectorLog, Warning, TEXT("There was no save file URL!"));

        return false;
    }
}
NS_IMETHODIMP nsPop3IncomingServer::MarkMessages()
{
  nsresult rv;
  if (m_runningProtocol)
    rv = m_runningProtocol->MarkMessages(&m_uidlsToMark);
  else
  {
    nsCString hostName;
    nsCString userName;
    nsCOMPtr<nsIFile> localPath;

    GetLocalPath(getter_AddRefs(localPath));

    GetHostName(hostName);
    GetUsername(userName);
    // do it all in one fell swoop
    rv = nsPop3Protocol::MarkMsgForHost(hostName.get(), userName.get(), localPath, m_uidlsToMark);
  }
  uint32_t count = m_uidlsToMark.Length();
  for (uint32_t i = 0; i < count; i++)
  {
    Pop3UidlEntry *ue = m_uidlsToMark[i];
    PR_Free(ue->uidl);
    PR_Free(ue);
  }
  m_uidlsToMark.Clear();
  return rv;
}
Beispiel #3
0
		void PrintInfo()
		{
			std::cout << "system information" << std::endl;
			log::Indenter indenter;
			if (*CVAR(logHost))
			{
				try
				{
					std::string
						user(GetUsername()),
						host(GetHostname());
					std::cout << "host is " << user << " on " << host << std::endl;
				}
				catch (...) {}
			}
			try
			{
				std::string platform(GetOs());
				std::cout << "platform is " << platform << std::endl;
			}
			catch (...) {}
			try
			{
				std::string machine(GetCpu());
				std::cout << "machine is " << machine << std::endl;
			}
			catch (...) {}
		}
 void OrthancPeerParameters::ToJson(Json::Value& value) const
 {
   value = Json::arrayValue;
   value.append(GetUrl());
   value.append(GetUsername());
   value.append(GetPassword());
 }
nsCString
nsSmtpServer::GetServerURIInternal(const bool aIncludeUsername)
{
  nsCString uri(NS_LITERAL_CSTRING("smtp://"));
  nsresult rv;

  if (aIncludeUsername)
  {
    nsCString username;
    rv = GetUsername(username);

    if (NS_SUCCEEDED(rv) && !username.IsEmpty()) {
      nsCString escapedUsername;
      MsgEscapeString(username, nsINetUtil::ESCAPE_XALPHAS, escapedUsername);
      // not all servers have a username
      uri.Append(escapedUsername);
      uri.AppendLiteral("@");
    }
  }

  nsCString hostname;
  rv = GetHostname(hostname);

  if (NS_SUCCEEDED(rv) && !hostname.IsEmpty()) {
    nsCString escapedHostname;
    MsgEscapeString(hostname, nsINetUtil::ESCAPE_URL_PATH, escapedHostname);
    // not all servers have a hostname
    uri.Append(escapedHostname);
  }

  return uri;
}
NS_IMETHODIMP
nsUserInfo::GetEmailAddress(char * *aEmailAddress)
{
    // use username + "@" + domain for the email address

    nsresult rv;

    nsCAutoString emailAddress;
    nsXPIDLCString username;
    nsXPIDLCString domain;

    rv = GetUsername(getter_Copies(username));
    if (NS_FAILED(rv)) return rv;

    rv = GetDomain(getter_Copies(domain));
    if (NS_FAILED(rv)) return rv;

    if (!username.IsEmpty() && !domain.IsEmpty()) {
        emailAddress = (const char *)username;
        emailAddress += "@";
        emailAddress += (const char *)domain;
    }
    else {
        return NS_ERROR_FAILURE;
    }

    *aEmailAddress = ToNewCString(emailAddress);

    return NS_OK;
}
Beispiel #7
0
NS_IMETHODIMP
nsSmtpServer::GetServerURI(nsACString &aResult)
{
    nsCAutoString uri(NS_LITERAL_CSTRING("smtp://"));

    nsCString username;
    nsresult rv = GetUsername(username);

    if (NS_SUCCEEDED(rv) && !username.IsEmpty()) {
        nsCString escapedUsername;
        MsgEscapeString(username, nsINetUtil::ESCAPE_XALPHAS, escapedUsername);
        // not all servers have a username
        uri.Append(escapedUsername);
        uri.AppendLiteral("@");
    }

    nsCString hostname;
    rv = GetHostname(hostname);

    if (NS_SUCCEEDED(rv) && !hostname.IsEmpty()) {
        nsCString escapedHostname;
        *((char **)getter_Copies(escapedHostname)) =
            nsEscape(hostname.get(), url_Path);
        // not all servers have a hostname
        uri.Append(escapedHostname);
    }

    aResult = uri;
    return NS_OK;
}
NS_IMETHODIMP
nsSmtpServer::GetUsernamePasswordWithUI(const PRUnichar * aPromptMessage, const
                                PRUnichar *aPromptTitle,
                                nsIAuthPrompt* aDialog,
                                nsACString &aUsername,
                                nsACString &aPassword)
{
  nsresult rv;
  if (!m_password.IsEmpty())
  {
    rv = GetUsername(aUsername);
    NS_ENSURE_SUCCESS(rv, rv);

    return GetPassword(aPassword);
  }

  NS_ENSURE_ARG_POINTER(aDialog);

  nsCString serverUri;
  rv = GetServerURI(serverUri);
  NS_ENSURE_SUCCESS(rv, rv);

  nsString uniUsername;
  nsString uniPassword;
  bool okayValue = true;

  rv = aDialog->PromptUsernameAndPassword(aPromptTitle, aPromptMessage,
                                          NS_ConvertASCIItoUTF16(serverUri).get(),
                                          nsIAuthPrompt::SAVE_PASSWORD_PERMANENTLY,
                                          getter_Copies(uniUsername),
                                          getter_Copies(uniPassword),
                                          &okayValue);
  NS_ENSURE_SUCCESS(rv, rv);

  // If the user pressed cancel, just return emtpy strings.
  if (!okayValue)
  {
    aUsername.Truncate();
    aPassword.Truncate();
    return rv;
  }

  // We got a username and password back...so remember them.
  NS_LossyConvertUTF16toASCII username(uniUsername);

  rv = SetUsername(username);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_LossyConvertUTF16toASCII password(uniPassword);

  rv = SetPassword(password);
  NS_ENSURE_SUCCESS(rv, rv);

  aUsername = username;
  aPassword = password;
  return NS_OK;
}
Beispiel #9
0
NS_IMETHODIMP
nsSmtpServer::ForgetPassword()
{
  nsresult rv;
  nsCOMPtr<nsILoginManager> loginMgr =
    do_GetService(NS_LOGINMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get the current server URI without the username
  nsCAutoString serverUri(NS_LITERAL_CSTRING("smtp://"));

  nsCString hostname;
  rv = GetHostname(hostname);

  if (NS_SUCCEEDED(rv) && !hostname.IsEmpty()) {
    nsCString escapedHostname;
    *((char **)getter_Copies(escapedHostname)) =
      nsEscape(hostname.get(), url_Path);
    // not all servers have a hostname
    serverUri.Append(escapedHostname);
  }

  PRUint32 count;
  nsILoginInfo** logins;

  NS_ConvertUTF8toUTF16 currServer(serverUri);

  nsCString serverCUsername;
  rv = GetUsername(serverCUsername);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ConvertUTF8toUTF16 serverUsername(serverCUsername);

  rv = loginMgr->FindLogins(&count, currServer, EmptyString(),
                            currServer, &logins);
  NS_ENSURE_SUCCESS(rv, rv);

  // There should only be one-login stored for this url, however just in case
  // there isn't.
  nsString username;
  for (PRUint32 i = 0; i < count; ++i)
  {
    if (NS_SUCCEEDED(logins[i]->GetUsername(username)) &&
        username.Equals(serverUsername))
    {
      // If this fails, just continue, we'll still want to remove the password
      // from our local cache.
      loginMgr->RemoveLogin(logins[i]);
    }
  }
  NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(count, logins);

  rv = SetPassword(EmptyCString());
  m_logonFailed = PR_TRUE;
  return rv;
}
Beispiel #10
0
	//------------------------------------------------------------------------------
	void PostHandle::_OnStart()
	{
		SmartPtr<PostJob> pPostJob( NEW PostJob );
		pPostJob->SetUrl(GetUrl());
		pPostJob->SetPostContent(_GetPostContent().c_str());
		pPostJob->SetUsername(GetUsername());
		pPostJob->SetPassword(GetPassword());
		pPostJob->Connect();
		pPostJob->SetCallback( MEMBER_FUNC_PTR( &PostHandle::JobDoneCallBack ));
		_PushJob( pPostJob );
	}
NS_IMETHODIMP
nsNntpUrl::GetServer(nsIMsgIncomingServer **aServer)
{
  NS_ENSURE_ARG_POINTER(aServer);
  
  nsresult rv;
  nsAutoCString scheme, user, host;

  GetScheme(scheme);
  GetUsername(user);
  GetHost(host);

  // No authority -> no server
  if (host.IsEmpty())
  {
    *aServer = nullptr;
    return NS_OK;
  }

  // Looking up the server...
  // news-message is used purely internally, so it can never refer to the real
  // attribute. nntp is never used internally, so it probably refers to the real
  // one. news is used both internally and externally, so it could refer to
  // either one. We'll assume it's an internal one first, though.
  bool isNews = scheme.EqualsLiteral("news") || scheme.EqualsLiteral("snews");
  bool isNntp = scheme.EqualsLiteral("nntp") || scheme.EqualsLiteral("nntps");
  
  bool tryReal = isNntp;

  nsCOMPtr<nsIMsgAccountManager> accountManager = 
    do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Ignoring return results: it is perfectly acceptable for the server to not
  // exist, but FindServer (and not FindRealServer) throws NS_ERROR_UNEXPECTED
  // in this case.
  *aServer = nullptr;
  if (tryReal)
    accountManager->FindRealServer(user, host, NS_LITERAL_CSTRING("nntp"), 0,
      aServer);
  else
    accountManager->FindServer(user, host, NS_LITERAL_CSTRING("nntp"), aServer);
  if (!*aServer && (isNews || isNntp))
  {
    // Didn't find it, try the other option
    if (tryReal)
      accountManager->FindServer(user, host, NS_LITERAL_CSTRING("nntp"),
        aServer);
    else
      accountManager->FindRealServer(user, host, NS_LITERAL_CSTRING("nntp"), 0,
        aServer);
  }
  return NS_OK;
}
Beispiel #12
0
// mscott - i think this function can be obsoleted and its functionality
// moved into SetSpec or an init method....
nsresult nsSmtpUrl::ParseUrl()
{
  nsresult rv = NS_OK;
  
  // set the username
  nsCAutoString userName;
  rv = GetUsername(userName);
  if (NS_FAILED(rv)) return rv; 
  m_userName = userName;
  
  return NS_OK;
}
nsresult
nsSmtpServer::GetPasswordWithoutUI()
{
  nsresult rv;
  nsCOMPtr<nsILoginManager> loginMgr(do_GetService(NS_LOGINMANAGER_CONTRACTID,
                                                   &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ConvertASCIItoUTF16 serverUri(GetServerURIInternal(false));

  uint32_t numLogins = 0;
  nsILoginInfo** logins = nullptr;
  rv = loginMgr->FindLogins(&numLogins, serverUri, EmptyString(),
                            serverUri, &logins);
  // Login manager can produce valid fails, e.g. NS_ERROR_ABORT when a user
  // cancels the master password dialog. Therefore handle that here, but don't
  // warn about it.
  if (NS_FAILED(rv))
    return rv;

  // Don't abort here, if we didn't find any or failed, then we'll just have
  // to prompt.
  if (numLogins > 0)
  {
    nsCString serverCUsername;
    rv = GetUsername(serverCUsername);
    NS_ConvertASCIItoUTF16 serverUsername(serverCUsername);

    nsString username;
    for (uint32_t i = 0; i < numLogins; ++i)
    {
      rv = logins[i]->GetUsername(username);
      NS_ENSURE_SUCCESS(rv, rv);

      if (username.Equals(serverUsername))
      {
        nsString password;
        rv = logins[i]->GetPassword(password);
        NS_ENSURE_SUCCESS(rv, rv);

        LossyCopyUTF16toASCII(password, m_password);
        break;
      }
    }
  }
  NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(numLogins, logins);
  return NS_OK;
}
Beispiel #14
0
void clSSH::Connect(int seconds)
{
    m_session = ssh_new();
    if(!m_session) { throw clException("ssh_new failed!"); }

    ssh_set_blocking(m_session, 0);
    int verbosity = SSH_LOG_NOLOG;
    ssh_options_set(m_session, SSH_OPTIONS_HOST, m_host.mb_str(wxConvUTF8).data());
    ssh_options_set(m_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
    ssh_options_set(m_session, SSH_OPTIONS_PORT, &m_port);
    ssh_options_set(m_session, SSH_OPTIONS_USER, GetUsername().mb_str().data());

    // Connect the session
    int retries = seconds * 100;
    if(retries < 0) { retries = 1; }
    DoConnectWithRetries(retries);
    ssh_set_blocking(m_session, 1);
}
Beispiel #15
0
void DefaultKeyboard::Setup(const Frontend::KeyboardConfig& config) {
    SoftwareKeyboard::Setup(config);

    auto cfg = Service::CFG::GetModule(Core::System::GetInstance());
    ASSERT_MSG(cfg, "CFG Module missing!");
    std::string username = Common::UTF16ToUTF8(cfg->GetUsername());
    switch (this->config.button_config) {
    case ButtonConfig::None:
    case ButtonConfig::Single:
        Finalize(username, 0);
        break;
    case ButtonConfig::Dual:
        Finalize(username, 1);
        break;
    case ButtonConfig::Triple:
        Finalize(username, 2);
        break;
    default:
        UNREACHABLE();
    }
}
Beispiel #16
0
/**
 * The main entry point for the application.
 */
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, gWindowTitle, sizeof(gWindowTitle));
	LoadString(hInstance, IDC_STREAMING, gWindowClass, sizeof(gWindowClass));

	// Register the window class
	RegisterWindowClass(hInstance);

	// Perform application initialization:
	if ( !InitInstance(hInstance, nCmdShow) )
	{
		return FALSE;
	}

	// Set the view to the default position
	ResetView();

	// Cache the last mouse position
	GetCursorPos(&gLastMousePos);

	// Initialize the Twitch SDK
	InitializeStreaming("<username>", "<password>", "<clientId>", "<clientSecret>", GetIntelDllPath());

	// Main message loop
	MSG msg;
	while (true)
	{
		// Check to see if any messages are waiting in the queue
		while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
		{
			// Process window messages
			TranslateMessage(&msg);
			DispatchMessage(&msg);

			// Received a quit message
			if (msg.message == WM_QUIT)
			{
				break;
			}
		}

		// Received a quit message so exit the app
		if (msg.message == WM_QUIT)
		{
			break;
		}

		if (gReinitializeRequired)
		{
			gReinitializeRequired = false;
			InitializeRendering();
		}

		// Draw the scene
		RenderScene();

		UpdateWaveMesh();

		// Process user input independent of the event queue
		if (gFocused)
		{
			HandleInput();
		}

		// Record the frame time
		unsigned __int64 curTime = GetSystemTimeMs();

		// Begin streaming when ready
		if (gStreamingDesired && 
			!IsStreaming() &&
			IsReadyToStream())
		{
			StartStreaming(gBroadcastWidth, gBroadcastHeight, gBroadcastFramesPerSecond);

			gLastCaptureTime = 0;
		}

		// If you send frames too quickly to the SDK (based on the broadcast FPS you configured) it will not be able 
		// to make use of them all.  In that case, it will simply release buffers without using them which means the
		// game wasted time doing the capture.  To mitigate this, the app should pace the captures to the broadcast FPS.
		unsigned __int64 captureDelta = curTime - gLastCaptureTime;
		bool isTimeForNextCapture = (captureDelta / 1000.0) >= (1.0 / gBroadcastFramesPerSecond);

		// streaming is in progress so try and capture a frame
		if (IsStreaming() && 
			!gPaused &&
			isTimeForNextCapture)
		{
			// capture a snapshot of the back buffer
			unsigned char* pBgraFrame = nullptr;
			int width = 0;
			int height = 0;
			bool gotFrame = false;

			switch (gCaptureMethod)
			{
			case CaptureMethod::Slow:
				gotFrame = CaptureFrame_Slow(gBroadcastWidth, gBroadcastHeight, pBgraFrame);
				break;
			case CaptureMethod::Fast:
				gotFrame = CaptureFrame_Fast(gBroadcastWidth, gBroadcastHeight, pBgraFrame, width, height);
				break;
			}

			// send a frame to the stream
			if (gotFrame)
			{
				SubmitFrame(pBgraFrame);
			}
		}

		// The SDK may generate events that need to be handled by the main thread so we should handle them
		FlushStreamingEvents();

		unsigned __int64 timePerFrame = curTime - gLastFrameTime;
		unsigned int fps = 0;
		if (timePerFrame > 0)
		{
			fps = static_cast<int>(1000 / timePerFrame);
		}
		gLastFrameTime = curTime;

		// Update the window title to show the state
		#undef STREAM_STATE
		#define STREAM_STATE(__state__) #__state__,

		char buffer[128];
		const char* streamStates[] = 
		{
			STREAM_STATE_LIST
		};
		#undef STREAM_STATE

		sprintf_s(buffer, sizeof(buffer), "Twitch Direct3D Streaming Sample - %s - %s    FPS=%d", GetUsername().c_str(), streamStates[GetStreamState()], fps);
		SetWindowTextA(gWindowHandle, buffer);
	}

	// Shutdown the Twitch SDK
	StopStreaming();
	ShutdownStreaming();

	// Cleanup the rendering method
	switch (gCaptureMethod)
	{
	case CaptureMethod::Slow:
		DeinitRendering_Slow();
		break;
	case CaptureMethod::Fast:
		DeinitRendering_Fast();
		break;
	}

	// Shutdown the app
	gGraphicsDevice->Release();
	gDirect3D->Release();

	// Cleanup the mesh
	DestroyWaveMesh();

	return (int)msg.wParam;
}
NS_IMETHODIMP
nsSmtpServer::GetPassword(nsACString& aPassword)
{
    if (m_password.IsEmpty() && !m_logonFailed)
    {
      // try to avoid prompting the user for another password. If the user has set
      // the appropriate pref, we'll use the password from an incoming server, if
      // the user has already logged onto that server.

      // if this is set, we'll only use this, and not the other prefs
      // user_pref("mail.smtpserver.smtp1.incomingAccount", "server1");

      // if this is set, we'll accept an exact match of user name and server
      // user_pref("mail.smtp.useMatchingHostNameServer", true);

      // if this is set, and we don't find an exact match of user and host name,
      // we'll accept a match of username and domain, where domain
      // is everything after the first '.'
      // user_pref("mail.smtp.useMatchingDomainServer", true);

      nsCString accountKey;
      bool useMatchingHostNameServer = false;
      bool useMatchingDomainServer = false;
      mPrefBranch->GetCharPref("incomingAccount", getter_Copies(accountKey));

      nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID);
      nsCOMPtr<nsIMsgIncomingServer> incomingServerToUse;
      if (accountManager)
      {
        if (!accountKey.IsEmpty())
          accountManager->GetIncomingServer(accountKey, getter_AddRefs(incomingServerToUse));
        else
        {
          nsresult rv;
          nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
          NS_ENSURE_SUCCESS(rv,rv);
          prefBranch->GetBoolPref("mail.smtp.useMatchingHostNameServer", &useMatchingHostNameServer);
          prefBranch->GetBoolPref("mail.smtp.useMatchingDomainServer", &useMatchingDomainServer);
          if (useMatchingHostNameServer || useMatchingDomainServer)
          {
            nsCString userName;
            nsCString hostName;
            GetHostname(hostName);
            GetUsername(userName);
            if (useMatchingHostNameServer)
              // pass in empty type and port=0, to match imap and pop3.
              accountManager->FindRealServer(userName, hostName, EmptyCString(), 0, getter_AddRefs(incomingServerToUse));
            int32_t dotPos = -1;
            if (!incomingServerToUse && useMatchingDomainServer
              && (dotPos = hostName.FindChar('.')) != kNotFound)
            {
              hostName.Cut(0, dotPos);
              nsCOMPtr<nsISupportsArray> allServers;
              accountManager->GetAllServers(getter_AddRefs(allServers));
              if (allServers)
              {
                uint32_t count = 0;
                allServers->Count(&count);
                uint32_t i;
                for (i = 0; i < count; i++)
                {
                  nsCOMPtr<nsIMsgIncomingServer> server = do_QueryElementAt(allServers, i);
                  if (server)
                  {
                    nsCString serverUserName;
                    nsCString serverHostName;
                    server->GetRealUsername(serverUserName);
                    server->GetRealHostName(serverHostName);
                    if (serverUserName.Equals(userName))
                    {
                      int32_t serverDotPos = serverHostName.FindChar('.');
                      if (serverDotPos != kNotFound)
                      {
                        serverHostName.Cut(0, serverDotPos);
                        if (serverHostName.Equals(hostName))
                        {
                          incomingServerToUse = server;
                          break;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      if (incomingServerToUse)
        return incomingServerToUse->GetPassword(aPassword);
    }
    aPassword = m_password;
    return NS_OK;
}
Beispiel #18
0
/* Get the next eventlog message */
char * EventlogNext(EventList ignore_list[MAX_IGNORED_EVENTS], int log, int * level)
{
	BOOL reopen = FALSE;
	DWORD errnum;
	DWORD needed;
	DWORD loglevel;
	EVENTLOGRECORD * event;
	char * cp;
	char * current;
	char * formatted_string;
	char * message_file;
	char * source;
	char * string_array[EVENTLOG_ARRAY_SZ];
	char * username;
	char hostname[HOSTNAME_SZ];
	char defmsg[ERRMSG_SZ];
	int event_id;
	int i;
	char *index;

	static char message[SYSLOG_DEF_SZ-17];
	static char tstamped_message[SYSLOG_DEF_SZ];

	/* Initialize array to prevent memory exceptions with bad message definitions */
	for(i = 0; i < EVENTLOG_ARRAY_SZ; i++)
		string_array[i]="*";

	/* Are there any records left in buffer */
	while (EventlogList[log].pos == EventlogList[log].count) {

		/* Reset input position */
		EventlogList[log].count = 0;
		EventlogList[log].pos = 0;

		/* Read a record */
		needed = 0;
		if (ReadEventLog(EventlogList[log].handle, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ, EventlogList[log].recnum, EventlogList[log].buffer, sizeof(EventlogList[log].buffer), &EventlogList[log].count, &needed) == 0) {

			/* Check error */
			errnum = GetLastError();
			switch (errnum) {

			/* Message too large... skip over */
			case ERROR_INSUFFICIENT_BUFFER:
				Log(LOG_WARNING, "Eventlog message size too large: \"%s\": %u bytes", EventlogList[log].name, needed);
				EventlogList[log].recnum++;
				break;

			/* Eventlog corrupted (?)... Reopen */
			case ERROR_EVENTLOG_FILE_CORRUPT:
				Log(LOG_INFO, "Eventlog was corrupted: \"%s\"", EventlogList[log].name);
				reopen = TRUE;
				break;

			/* Eventlog files are clearing... Reopen */
			case ERROR_EVENTLOG_FILE_CHANGED:
				Log(LOG_INFO, "Eventlog was cleared: \"%s\"", EventlogList[log].name);
				reopen = TRUE;
				break;

			/* Record not available (yet) */
			case ERROR_INVALID_PARAMETER:
				return NULL;

			/* Normal end of eventlog messages */
			case ERROR_HANDLE_EOF:
				return NULL;

			/* Eventlog probably closing down */
			case RPC_S_UNKNOWN_IF:
				return NULL;

			/* Unknown condition */
			default:
				Log(LOG_ERROR|LOG_SYS, "Eventlog \"%s\" returned error: ", EventlogList[log].name);
				ServiceIsRunning = FALSE;
				return NULL;
			}

			/* Process reopen */
			if (reopen) {
				EventlogClose(log);
				if (EventlogOpen(log)) {
					ServiceIsRunning = FALSE;
					return NULL;
				}
				reopen = FALSE;
			}
		}
	}

	/* Increase record number */
	EventlogList[log].recnum++;

	/* Get position into buffer */
	current = EventlogList[log].buffer + EventlogList[log].pos;

	/* Get pointer to current event record */
	event = (EVENTLOGRECORD *) current;

	/* Advance position */
	EventlogList[log].pos += event->Length;

	/* Get source and event id */
	source = current + sizeof(*event);
	event_id = (int) HRESULT_CODE(event->EventID);
	
	/* Check Event Info Against Ignore List */
	if (IgnoreSyslogEvent(ignore_list, source, event_id)) {
		if (LogInteractive)
			printf("IGNORING_EVENT: SOURCE=%s & ID=%i\n", source, event_id);
		return NULL;
	}
	
	/* Check number of strings */
	if (event->NumStrings > COUNT_OF(string_array)) {

		/* Too many strings */
		Log(LOG_WARNING, "Eventlog message has too many strings to print message: \"%s\": %u strings", EventlogList[log].name, event->NumStrings);
		formatted_string = NULL;
	} else {

		/* Convert strings to arrays */
		cp = current + event->StringOffset;
		for (i = 0; i < event->NumStrings; i++) {
			string_array[i] = cp;
			while (*cp++ != '\0');
		}

		message_file = LookupMessageFile(EventlogList[log].name, source, event->EventID);

		if (message_file == NULL) {
			/* Cannot load resources */
			formatted_string = NULL;
		} else {
			/* Format eventlog message */
			formatted_string = FormatLibraryMessage(message_file, event->EventID, string_array);
		}
	}

	/* Create a default message if resources or formatting didn't work */
	if (formatted_string == NULL) {
		_snprintf_s(defmsg, sizeof(defmsg), _TRUNCATE,
			"(Facility: %u, Status: %s)",
			HRESULT_FACILITY(event->EventID),
			FAILED(event->EventID) ? "Failure" : "Success"
		);
		formatted_string = defmsg;
	}

	/* replace every space in source by underscores */
	index = source;
	while( *index ) {
		if( *index == ' ' ) {
			*index = '_';
		}
		index++;
	}

	/* Format source and event ID number */
	if(SyslogIncludeTag) {
		_snprintf_s(message, sizeof(message), _TRUNCATE,
			"%s: %s: %u: ",
			SyslogTag,
			source,
			HRESULT_CODE(event->EventID)
		);
	} else {
		_snprintf_s(message, sizeof(message), _TRUNCATE,
			"%s: %u: ",
			source,
			HRESULT_CODE(event->EventID)
		);
	}

	/* Convert user */
	if (event->UserSidLength > 0) {
		username = GetUsername((SID *) (current + event->UserSidOffset));
		if (username) {
			strncat_s(message, sizeof(message), username, _TRUNCATE);
			strncat_s(message, sizeof(message), ": ", _TRUNCATE);
		}
	}

	/* Add formatted string to base message */
	strncat_s(message, sizeof(message), formatted_string, _TRUNCATE);

	/* Select syslog level */
	switch (event->EventType) {
		case EVENTLOG_ERROR_TYPE:
			loglevel = SYSLOG_ERR;
			*level = SYSLOG_BUILD(SyslogFacility, loglevel);
			break;
		case EVENTLOG_WARNING_TYPE:
			loglevel = SYSLOG_WARNING;
			*level = SYSLOG_BUILD(SyslogFacility, loglevel);
			break;
		case EVENTLOG_INFORMATION_TYPE:
			loglevel = SYSLOG_NOTICE;
			*level = SYSLOG_BUILD(SyslogFacility, loglevel);
			break;
		case EVENTLOG_AUDIT_SUCCESS:
            strncat_s(message, sizeof(message), "AUDIT_SUCCESS ", _TRUNCATE);
			loglevel = SYSLOG_NOTICE;
			*level = SYSLOG_BUILD(SyslogFacility, loglevel);
			break;
		case EVENTLOG_AUDIT_FAILURE:
            strncat_s(message, sizeof(message), "AUDIT_FAILURE ", _TRUNCATE);
			loglevel = SYSLOG_ERR;
			*level = SYSLOG_BUILD(SyslogFacility, loglevel);
			break;

		/* Everything else */
		case EVENTLOG_SUCCESS:
		default:
			loglevel = SYSLOG_NOTICE;
			*level = SYSLOG_BUILD(SyslogFacility, loglevel);
			break;
	}

	/* If event is not being ignored, make sure it is severe enough to be logged */
	if (SyslogLogLevel != 0)
		if (SyslogLogLevel < loglevel-1)
			return NULL;

	/* Add hostname for RFC compliance (RFC 3164) */
	/* if -a then use the fqdn bound to our IP address. If none, use the IP address */
	if (ProgramUseIPAddress == TRUE) {
		strcpy_s(hostname, HOSTNAME_SZ, ProgramHostName);
	} else {
		if (ExpandEnvironmentStrings("%COMPUTERNAME%", hostname, COUNT_OF(hostname)) == 0) {
			strcpy_s(hostname, COUNT_OF(hostname), "HOSTNAME_ERR");
			Log(LOG_ERROR|LOG_SYS, "Cannot expand %COMPUTERNAME%");
	    }
    }
	
	/* Query and Add timestamp from EventLog, add hostname, */
	/* and finally the message to the string */
	_snprintf_s(tstamped_message, sizeof(tstamped_message), _TRUNCATE,
		"%s %s %s",
		TimeToString(event->TimeGenerated),
		hostname,
		message
	);

	/* Return formatted message */
	return tstamped_message;
}
Beispiel #19
0
/**
* Uploads the save file to CloudyWeb.
*
* @param Filename               Filename of the save game file.
* @param PlayerControllerId     PlayerControllerId of the player who is saving the game.
*
* @return Returns true if the file upload was successful. Else, returns false.
*
*/
bool CloudyWebAPIImpl::UploadFile(FString Filename, int32 PlayerControllerId)
{
    bool RequestSuccess = false;

    CURL *curl;
    CURLcode res;
    std::string readBuffer;
    
    FString Url = BaseUrl + SaveDataUrl;
    std::string UrlCString(TCHAR_TO_UTF8(*Url));
    
    // Filepath of .sav file
    FString Filepath = FPaths::GameDir();
    Filepath += "Saved/SaveGames/" + Filename + ".sav";
    std::string filePath(TCHAR_TO_UTF8(*Filepath));
    
    // Get game name
    FString GameName = FApp::GetGameName();
    std::string gameName(TCHAR_TO_UTF8(*GameName));

    // Get game ID
    FString GameID = FString::FromInt(GetGameId());
    std::string GameIDCString(TCHAR_TO_UTF8(*GameID));

    // Get username
    FString Username = GetUsername(PlayerControllerId);
    std::string UsernameCString(TCHAR_TO_UTF8(*Username));
    
    // Convert PlayerControllerId
    FString playerControllerIdFString = FString::FromInt(PlayerControllerId);
    std::string playerControllerId(TCHAR_TO_UTF8(*playerControllerIdFString));

    if (GetGameId() == -1 || Username.Equals("") || PlayerControllerId < 0)
    {
        UE_LOG(CloudyWebAPILog, Error, TEXT("The game ID, username, or player controller ID is invalid"));
        return false;
    }
    
    struct curl_httppost *formpost = NULL;
    struct curl_httppost *lastptr = NULL;
    struct curl_slist *headerlist = NULL;
    FString AuthHeader = "Authorization: Token " + Token;
    std::string AuthHeaderCString(TCHAR_TO_UTF8(*AuthHeader));
    
    curl_global_init(CURL_GLOBAL_ALL);
    
    /* Fill in the file upload field */
    curl_formadd(&formpost, &lastptr,
        CURLFORM_COPYNAME, "saved_file",
        CURLFORM_FILE, filePath.c_str(),
        CURLFORM_END);
    
    /* Fill in the player controller ID field */
    curl_formadd(&formpost, &lastptr,
        CURLFORM_COPYNAME, "user",
        CURLFORM_COPYCONTENTS, UsernameCString.c_str(),
        CURLFORM_END);
    
    /* Fill in the game name field */
    curl_formadd(&formpost, &lastptr,
        CURLFORM_COPYNAME, "game",
        CURLFORM_COPYCONTENTS, GameIDCString.c_str(),
        CURLFORM_END);
    
    curl = curl_easy_init();
    /* initialize custom header list (stating that Expect: 100-continue is not
    wanted */
    headerlist = curl_slist_append(headerlist, AuthHeaderCString.c_str());
    if (curl) {
        /* what URL that receives this POST */
        curl_easy_setopt(curl, CURLOPT_URL, UrlCString.c_str());

        /* only disable 100-continue header if explicitly requested */
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

        /* What form to send */
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
    
        /* Set up string to write response into */
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
    
        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* Check if the request was successful */
        if (res == CURLE_OK)
        {
            RequestSuccess = true;
        }
    
        /* always cleanup */
        curl_easy_cleanup(curl);
    
        /* then cleanup the formpost chain */
        curl_formfree(formpost);
        /* free slist */
        curl_slist_free_all(headerlist);
    
        UE_LOG(CloudyWebAPILog, Warning, TEXT("Response data: %s"), UTF8_TO_TCHAR(readBuffer.c_str()));
        ReadAndStoreSaveFileURL(readBuffer.c_str(), PlayerControllerId);
    }

    return RequestSuccess;
}