Ejemplo n.º 1
0
void
ActivateDialog::actionPerformed(Widget* source)
{
  if(source == mCancelButton) {
//     rGUIManager()->popDialog();
  }
  else if(source == mActivateButton) {
    License* currentLicense = ConfigManager::getCurrent()->getLicense();
    currentLicense->setPlayerEmail(wstringToString(mEmailField->getLabel()));

#ifndef SELF_TEST
    mLoadingDialog->show();
    mLoadingDialog->startTask(L"Activating..", 0.0f);
    currentLicense->updateLicenseKey();
    mLoadingDialog->hide();
#endif

    if(currentLicense->getType() == LICENSE_TRIAL) {
      mInstructions->setLabel(L"Email not found: Please enter valid ordering email");
      mEmailField->setLabel(L"");
    }
    else {
//       rGUIManager()->popDialog();
      if(mScriptCommand != "")
        LuaManager::getSingleton().doString(mScriptCommand);
    }    
  }
}
Ejemplo n.º 2
0
	std::vector<Docker::Model::Container> Client::getContainers() {
		http_client client(this->getBaseUrl() + L"containers/json");
		std::vector<Docker::Model::Container> containers;

		client.request(methods::GET).then([=](http_response response){
			return response.extract_json();
		}).then([&](pplx::task<json::value> previousTask) {
			json::value const & v = previousTask.get();

			for (int i = 0; i < v.size(); ++i) {
				json::value val = v.at(i);

				std::wstring W_Id = val[U("Id")].as_string();
				std::wstring W_Image = val[U("Image")].as_string();
				std::wstring W_Name = val[U("Names")].as_array()[0].as_string();
				std::wstring W_Status = val[U("Status")].as_string();
				std::wstring W_Command = val[U("Command")].as_string();
				unsigned int Created = val[U("Created")].as_integer();

				std::string Id = wstringToString(W_Id);
				std::string Image = wstringToString(W_Image);
				std::string Name = wstringToString(W_Name);
				std::string Status = wstringToString(W_Status);
				std::string Command = wstringToString(W_Command);

				Docker::Model::Container container;
				container.Id = Id;
				container.Image = Image;
				container.Name = Name;
				container.Created = Created;
				container.Status = Status;
				container.Command = Command;

				containers.push_back(container);
			}
		}).wait();

		return containers;

	}
Ejemplo n.º 3
0
QueryData genUsers(QueryContext& context) {
  QueryData results;

  // USER_INFO_3 conains generic user information
  LPUSER_INFO_3 pUserBuffer = nullptr;
  DWORD dwGenericUserLevel = 3;
  DWORD dwPreferredMaxLength = MAX_PREFERRED_LENGTH;
  DWORD dwEntriesRead = 0;
  DWORD dwTotalEntries = 0;
  DWORD dwResumeHandle = 0;
  NET_API_STATUS nEnumStatus;

  nEnumStatus = NetUserEnum(nullptr,
                            dwGenericUserLevel,
                            FILTER_NORMAL_ACCOUNT,
                            (LPBYTE*)&pUserBuffer,
                            dwPreferredMaxLength,
                            &dwEntriesRead,
                            &dwTotalEntries,
                            &dwResumeHandle);

  // We save the original pointer to the USER_INFO_3 buff for mem management
  LPUSER_INFO_3 pUserIterationBuffer = pUserBuffer;
  if (pUserIterationBuffer == nullptr || nEnumStatus != NERR_Success) {
    if (pUserBuffer != nullptr) {
      NetApiBufferFree(pUserBuffer);
    }
    return results;
  }

  for (DWORD i = 0; i < dwEntriesRead; i++) {
    Row r;
    r["username"] = wstringToString(pUserIterationBuffer->usri3_name);
    r["description"] = wstringToString(pUserIterationBuffer->usri3_comment);
    r["uid"] = BIGINT(pUserIterationBuffer->usri3_user_id);
    r["gid"] = BIGINT(pUserIterationBuffer->usri3_primary_group_id);
    r["uid_signed"] = r["uid"];
    r["gid_signed"] = r["gid"];
    r["shell"] = "C:\\Windows\\system32\\cmd.exe";

    // USER_INFO_23 contains detailed info, like the user Sid
    DWORD dwDetailedUserLevel = 23;
    LPUSER_INFO_23 pSidUserBuffer = nullptr;
    NET_API_STATUS nStatus;
    nStatus = NetUserGetInfo(nullptr,
                             pUserIterationBuffer->usri3_name,
                             dwDetailedUserLevel,
                             (LPBYTE*)&pSidUserBuffer);
    if (nStatus != NERR_Success) {
      if (pSidUserBuffer != nullptr) {
        NetApiBufferFree(pSidUserBuffer);
        pSidUserBuffer = nullptr;
      }
      continue;
    }

    LPTSTR sStringSid = nullptr;
    auto ret =
        ConvertSidToStringSid(pSidUserBuffer->usri23_user_sid, &sStringSid);
    if (ret == 0) {
      if (pSidUserBuffer != nullptr) {
        NetApiBufferFree(pSidUserBuffer);
      }
      continue;
    }
    r["uuid"] = sStringSid;
    std::string query = "SELECT LocalPath FROM Win32_UserProfile where SID=\"" +
                        std::string(sStringSid) + "\"";
    WmiRequest wmiRequest(query);
    std::vector<WmiResultItem>& wmiResults = wmiRequest.results();
    if (wmiResults.size() != 0) {
      wmiResults[0].GetString("LocalPath", r["directory"]);
    }
    LocalFree(sStringSid);
    NetApiBufferFree(pSidUserBuffer);

    results.push_back(r);
    pUserIterationBuffer++;
  }
  NetApiBufferFree(pUserBuffer);

  if (nEnumStatus == ERROR_MORE_DATA) {
    LOG(WARNING)
        << "NetUserEnum contains more data: users table may be incomplete";
  }

  return results;
}
Ejemplo n.º 4
0
 inline tstring toTstring(std::wstring ws)   { return wstringToString(ws); }
Ejemplo n.º 5
0
 inline std::string toString(tstring s)      { return wstringToString(s); }
Ejemplo n.º 6
0
void enumerateTasksForFolder(std::string path, QueryData& results) {
  void* vpService = nullptr;
  auto ret = CoCreateInstance(CLSID_TaskScheduler,
                              nullptr,
                              CLSCTX_INPROC_SERVER,
                              IID_ITaskService,
                              &vpService);
  if (FAILED(ret)) {
    VLOG(1) << "Failed to create COM instance " << ret;
    return;
  }

  auto pService = static_cast<ITaskService*>(vpService);
  ret =
      pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
  if (FAILED(ret)) {
    VLOG(1) << "Failed to connect to TaskService " << ret;
    pService->Release();
    return;
  }

  ITaskFolder* pRootFolder = nullptr;
  auto widePath = stringToWstring(path);
  ret = pService->GetFolder(BSTR(widePath.c_str()), &pRootFolder);
  pService->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get root task folder " << ret;
    return;
  }

  IRegisteredTaskCollection* pTaskCollection = nullptr;
  ret = pRootFolder->GetTasks(TASK_ENUM_HIDDEN, &pTaskCollection);
  pRootFolder->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get task collection for root folder " << ret;
    return;
  }

  long numTasks = 0;
  pTaskCollection->get_Count(&numTasks);
  for (size_t i = 0; i < numTasks; i++) {
    IRegisteredTask* pRegisteredTask = nullptr;
    // Collections are 1-based lists
    ret = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);
    if (FAILED(ret)) {
      VLOG(1) << "Failed to process task";
      continue;
    }

    Row r;
    BSTR taskName;
    ret = pRegisteredTask->get_Name(&taskName);
    std::wstring wTaskName(taskName, SysStringLen(taskName));
    r["name"] = ret == S_OK ? SQL_TEXT(wstringToString(wTaskName.c_str())) : "";

    VARIANT_BOOL enabled = false;
    pRegisteredTask->get_Enabled(&enabled);
    r["enabled"] = enabled ? INTEGER(1) : INTEGER(0);

    TASK_STATE taskState;
    pRegisteredTask->get_State(&taskState);
    r["state"] = kStateMap.count(taskState) > 0
                     ? kStateMap.at(taskState)
                     : kStateMap.at(TASK_STATE_UNKNOWN);

    BSTR taskPath;
    ret = pRegisteredTask->get_Path(&taskPath);
    std::wstring wTaskPath(taskPath, SysStringLen(taskPath));
    r["path"] = ret == S_OK ? wstringToString(wTaskPath.c_str()) : "";

    VARIANT_BOOL hidden = false;
    pRegisteredTask->get_Enabled(&hidden);
    r["hidden"] = hidden ? INTEGER(1) : INTEGER(0);

    HRESULT lastTaskRun = E_FAIL;
    pRegisteredTask->get_LastTaskResult(&lastTaskRun);
    _com_error err(lastTaskRun);
    r["last_run_message"] = err.ErrorMessage();
    r["last_run_code"] = INTEGER(lastTaskRun);

    // We conver the COM Date type to a unix epoch timestamp
    DATE dRunTime;
    SYSTEMTIME st;
    FILETIME ft;
    FILETIME locFt;

    pRegisteredTask->get_LastRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["last_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    pRegisteredTask->get_NextRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["next_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    ITaskDefinition* taskDef = nullptr;
    IActionCollection* tActionCollection = nullptr;
    pRegisteredTask->get_Definition(&taskDef);
    if (taskDef != nullptr) {
      taskDef->get_Actions(&tActionCollection);
    }

    long actionCount = 0;
    if (tActionCollection != nullptr) {
      tActionCollection->get_Count(&actionCount);
    }
    std::vector<std::string> actions;

    // Task collections are 1-indexed
    for (auto j = 1; j <= actionCount; j++) {
      IAction* act = nullptr;
      IExecAction* execAction = nullptr;
      tActionCollection->get_Item(j, &act);
      if (act == nullptr) {
        continue;
      }
      act->QueryInterface(IID_IExecAction,
                          reinterpret_cast<void**>(&execAction));
      if (execAction == nullptr) {
        continue;
      }

      BSTR taskExecPath;
      execAction->get_Path(&taskExecPath);
      std::wstring wTaskExecPath(taskExecPath, SysStringLen(taskExecPath));

      BSTR taskExecArgs;
      execAction->get_Arguments(&taskExecArgs);
      std::wstring wTaskExecArgs(taskExecArgs, SysStringLen(taskExecArgs));

      BSTR taskExecRoot;
      execAction->get_WorkingDirectory(&taskExecRoot);
      std::wstring wTaskExecRoot(taskExecRoot, SysStringLen(taskExecRoot));

      auto full = wTaskExecRoot + L" " + wTaskExecPath + L" " + wTaskExecArgs;
      actions.push_back(wstringToString(full.c_str()));
      act->Release();
    }
    if (tActionCollection != nullptr) {
      tActionCollection->Release();
    }
    if (taskDef != nullptr) {
      taskDef->Release();
    }
    r["action"] = !actions.empty() ? osquery::join(actions, ",") : "";

    results.push_back(r);
    pRegisteredTask->Release();
  }
  pTaskCollection->Release();
}
Ejemplo n.º 7
0
void genInterfaceDetail(const IP_ADAPTER_ADDRESSES* adapter, Row& r) {
  r["interface"] = INTEGER(adapter->IfIndex);
  r["mtu"] = INTEGER(adapter->Mtu);
  r["type"] = INTEGER(adapter->IfType);
  r["description"] = wstringToString(adapter->Description);

  std::vector<std::string> toks;
  for (size_t i = 0; i < adapter->PhysicalAddressLength; i++) {
    std::stringstream ss;
    ss << std::hex;
    ss << static_cast<unsigned int>(adapter->PhysicalAddress[i]);
    auto s = ss.str();
    if (s.size() < 2_sz) {
      s = '0' + s;
    }
    toks.push_back(s);
  }
  r["mac"] = osquery::join(toks, ":");
  r["flags"] = INTEGER(adapter->Flags);
  r["metric"] = INTEGER(adapter->Ipv4Metric);

  // TODO: These values will need an equivalent on Windows systems
  r["last_change"] = BIGINT("-1");
  r["collisions"] = BIGINT("-1");

  // Grab the remaining table values from WMI
  auto query =
      "SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE "
      "Name = \"" +
      r["description"] + "\"";

  WmiRequest req1(query);
  if (req1.getStatus().ok()) {
    auto& results = req1.results();
    if (!results.empty()) {
      std::string sPlaceHolder;
      unsigned long long ullPlaceHolder = 0;

      results[0].GetString("PacketsReceivedPerSec", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["ipackets"] = BIGINT(ullPlaceHolder);
      results[0].GetString("PacketsSentPerSec", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["opackets"] = BIGINT(ullPlaceHolder);

      results[0].GetString("BytesReceivedPerSec", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["ibytes"] = BIGINT(ullPlaceHolder);
      results[0].GetString("BytesSentPerSec", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["obytes"] = BIGINT(ullPlaceHolder);

      results[0].GetString("PacketsReceivedErrors", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["ierrors"] = BIGINT(ullPlaceHolder);
      results[0].GetString("PacketsOutboundErrors", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["oerrors"] = BIGINT(ullPlaceHolder);

      results[0].GetString("PacketsReceivedDiscarded", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["idrops"] = BIGINT(ullPlaceHolder);
      results[0].GetString("PacketsOutboundDiscarded", sPlaceHolder);
      safeStrtoull(sPlaceHolder, 10, ullPlaceHolder);
      r["odrops"] = BIGINT(ullPlaceHolder);
    } else {
      LOG(INFO) << "Failed to retrieve network statistics for interface "
                << r["interface"];
    }
  }

  query =
      "SELECT * FROM Win32_NetworkAdapter WHERE "
      "InterfaceIndex = " +
      r["interface"];
  WmiRequest req2(query);
  if (req2.getStatus().ok()) {
    auto& results = req2.results();
    if (!results.empty()) {
      bool bPlaceHolder;
      long lPlaceHolder = 0;
      unsigned __int64 ullPlaceHolder = 0;
      results[0].GetString("Manufacturer", r["manufacturer"]);
      results[0].GetString("NetConnectionID", r["connection_id"]);
      results[0].GetLong("NetConnectionStatus", lPlaceHolder);
      r["connection_status"] = INTEGER(lPlaceHolder);
      results[0].GetBool("NetEnabled", bPlaceHolder);
      r["enabled"] = INTEGER(bPlaceHolder);
      results[0].GetBool("PhysicalAdapter", bPlaceHolder);
      r["physical_adapter"] = INTEGER(bPlaceHolder);
      results[0].GetString("ServiceName", r["service"]);
      results[0].GetUnsignedLongLong("Speed", ullPlaceHolder);
      r["speed"] = INTEGER(ullPlaceHolder);
    } else {
      LOG(INFO) << "Failed to retrieve physical state for interface "
                << r["interface"];
    }
  }

  query =
      "SELECT * FROM win32_networkadapterconfiguration WHERE "
      "InterfaceIndex = " +
      r["interface"];
  WmiRequest req3(query);
  if (req3.getStatus().ok()) {
    auto& results = req3.results();
    if (!results.empty()) {
      bool bPlaceHolder;
      std::vector<std::string> vPlaceHolder;
      results[0].GetBool("DHCPEnabled", bPlaceHolder);
      r["dhcp_enabled"] = INTEGER(bPlaceHolder);
      results[0].GetString("DHCPLeaseExpires", r["dhcp_lease_expires"]);
      results[0].GetString("DHCPLeaseObtained", r["dhcp_lease_obtained"]);
      results[0].GetString("DHCPServer", r["dhcp_server"]);
      results[0].GetString("DNSDomain", r["dns_domain"]);
      results[0].GetVectorOfStrings("DNSDomainSuffixSearchOrder", vPlaceHolder);
      r["dns_domain_suffix_search_order"] = osquery::join(vPlaceHolder, ", ");
      results[0].GetString("DNSHostName", r["dns_host_name"]);
      results[0].GetVectorOfStrings("DNSServerSearchOrder", vPlaceHolder);
      r["dns_server_search_order"] = osquery::join(vPlaceHolder, ", ");
    } else {
      LOG(INFO) << "Failed to retrieve DHCP and DNS information for interface "
                << r["interface"];
    }
  }
}
	// enumerates all network resources (hostnames)
	std::vector<std::string> getNetworkResourceNames(LPNETRESOURCE lpnr)
	{
		std::vector<std::string> hostnames;

		DWORD dwResult, dwResultEnum;
		HANDLE hEnum;
		DWORD cbBuffer = 16384;
		DWORD cEntries = -1;
		LPNETRESOURCE lpnrLocal;

		dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, // all network resources
								RESOURCETYPE_ANY,   // all resources
								0,					// enumerate all resources
								lpnr,				// (first time the function is called)
								&hEnum);			// handle to the resource


		lpnrLocal = (LPNETRESOURCE)GlobalAlloc(GPTR, cbBuffer);

		if (dwResult != NO_ERROR || lpnrLocal == NULL)
			return hostnames;

		do {
			// Initialize the buffer
			ZeroMemory(lpnrLocal, cbBuffer);

			// Enumerate the network resources
			dwResultEnum = WNetEnumResource(hEnum, &cEntries, lpnrLocal, &cbBuffer);

			if (dwResultEnum == NO_ERROR) {
				// loop through the structures
				for (int i = 0; i < cEntries; ++i) {
					std::string remoteName(wstringToString(lpnrLocal[i].lpRemoteName));

					// check if the resource name starts with '\\'
					if (remoteName.compare(0, 2, "\\\\") == 0) {
						remoteName = remoteName.substr(2);		// remove the first '\\'

						// find other slashes and remove them
						if (remoteName.find("\\") != std::string::npos)
							remoteName = remoteName.substr(0, remoteName.find("\\"));

						// add to the hostnames vector
						if (std::find(hostnames.begin(), hostnames.end(), remoteName) == hostnames.end())
							hostnames.push_back(remoteName);
					}

					// if the resource found is a resource container, call the function recursively
					if (RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) {
						std::vector<std::string> hn = getNetworkResourceNames(&lpnrLocal[i]);
						// append the vector returned by the recursive call to our vector
						if (!hn.empty())
							for (auto name : hn)
								if (std::find(hostnames.begin(), hostnames.end(), remoteName) == hostnames.end())
									hostnames.push_back(name);
					}
				}
			}
			else if (dwResultEnum != ERROR_NO_MORE_ITEMS)
				break;
		} while (dwResultEnum != ERROR_NO_MORE_ITEMS);

		// free the memory
		GlobalFree((HGLOBAL)lpnrLocal);

		// end enumeration
		dwResult = WNetCloseEnum(hEnum);

		if (dwResult != NO_ERROR)
			return std::vector<std::string>();		// empty vector

		return hostnames;
	}
Ejemplo n.º 9
0
std::string wstringToString(const wchar_t* str)
{
	std::wstring wstr(str);
	return wstringToString(wstr);
}
Ejemplo n.º 10
0
std::string Condition::getName(bool tip, NameFlags::Value flags, int recursion) const
{
    if (!tip) {
	    return (type < scen.pergame->max_condition_types) ? types[type] : "Unknown!";
	} else {
	    std::string stype = std::string("");
        std::ostringstream convert;
        switch (type) {
        case ConditionType::None:
            // Let this act like a separator
            convert << "                                                                                    ";
            stype.append(convert.str());
            break;
        case ConditionType::BringObjectToArea:
            convert << get_unit_full_name(object) << " " << object;
            convert << " is" << areaName();
            stype.append(convert.str());
            break;
        case ConditionType::BringObjectToObject:
            convert << get_unit_full_name(object) << " " << object << " is next to unit " << get_unit_full_name(u_loc) << " " << u_loc;
            stype.append(convert.str());
            break;
        case ConditionType::OwnObjects:
        case ConditionType::OwnFewerObjects:
        case ConditionType::ObjectsInArea:
            { // we define some variables in this block, therefore need scope as we are also in a case
                if (valid_player()) {
                    convert << playerPronoun(player) << " has ";
                }
                switch (type) {
                case ConditionType::OwnObjects:
                case ConditionType::ObjectsInArea:
                    if (amount == 0) {
                        convert << "any number of";
                    } else {
                        convert << "at least " << amount;
                    }
                    break;
                case ConditionType::OwnFewerObjects:
                    if (amount == 0) {
                        convert << "no";
                    } else {
                        convert << "at most " << amount;
                    }
                    break;
                }
                if (valid_unit_spec()) {
                    std::string un(wstringToString(pUnit->name()));
                    if (amount > 1 && !un.empty() && *un.rbegin() != 's' && !replaced(un, "man", "men")) {
                        convert << " " << un << "s";
                    } else {
                        convert << " " << un;
                    }
                } else {
                    if (amount != 1) {
                        convert << " units";
                    } else {
                        convert << " unit";
                    }
                }
                convert << areaName();
                stype.append(convert.str());
            }
            break;
        case ConditionType::DestroyObject:
            convert << get_unit_full_name(object) << " is killed";
            stype.append(convert.str());
            break;
        case ConditionType::CaptureObject:
            convert << playerPronoun(player) << " captured " << get_unit_full_name(object);
            stype.append(convert.str());
            break;
        case ConditionType::AccumulateAttribute:
            switch (res_type) {
            case 0: // Food accumulated
                convert << playerPronoun(player) << " has " << amount << " food";
                break;
            case 1: // Wood accumulated
                convert << playerPronoun(player) << " has " << amount << " wood";
                break;
            case 2: // Stone accumulated
                convert << playerPronoun(player) << " has " << amount << " stone";
                break;
            case 3: // Gold accumulated
                convert << playerPronoun(player) << " has " << amount << " gold";
                break;
            case 20: // Units killed
                if (amount == 1) {
                    convert << playerPronoun(player) << " kills a unit";
                } else {
                    convert << playerPronoun(player) << " has killed " << amount << " units";
                }
                break;
            case 44: // Kill ratio
                if (amount == 0) {
                    convert << playerPronoun(player) << " has equal kills and deaths";
                } else if (amount == 1) {
                    convert << playerPronoun(player) << " has killed one more than lost";
                } else if (amount > 0) {
                    convert << playerPronoun(player) << " has " << amount << " more kills than deaths";
                } else if (amount == -1) {
                    convert << playerPronoun(player) << " has lost one more unit than has killed";
                } else {
                    convert << playerPronoun(player) << " has " << -amount << " more deaths than kills";
                }
                break;
            default:
                //convert << types_short[type];
                if (res_type >= 0) {
                    const Link * list = esdata.resources.head();
	                for (int i=0; list; list = list->next(), i++)
	                {
		                if (i == res_type) {
                            std::wstring resname(list->name());
		                    convert << playerPronoun(player) << "'s ";
                            convert << std::string( resname.begin(), resname.end());
                            convert << " >= " << amount;
		                    break;
		                }
	                }
	            }
                break;
            }
            stype.append(convert.str());
            break;
        case ConditionType::ResearchTehcnology:
            if (valid_technology_spec()) {
                convert << playerPronoun(player) << " has tech ";
                std::wstring techname(pTech->name());
                convert << std::string( techname.begin(), techname.end());
                convert << " researched";
            } else {
                convert << "INVALID";
            }
            stype.append(convert.str());
            break;
        case ConditionType::ResearchingTechnology:
            if (pTech && pTech->id()) {
                convert << playerPronoun(player) << " is researching ";
                std::wstring techname(pTech->name());
                convert << std::string( techname.begin(), techname.end());
            } else {
                convert << "INVALID";
            }
            stype.append(convert.str());
            break;
        case ConditionType::Timer:
            convert << time_string(timer) << " has passed";
            stype.append(convert.str());
            break;
        case ConditionType::ObjectSelected:
            convert << "selected unit " << object;
            convert << " (" << get_unit_full_name(object) << ")";
            stype.append(convert.str());
            break;
        case ConditionType::AISignal:
            switch (ai_signal) {
            case -1034:
                convert << "singleplayer / cheats enabled";
                break;
            case -1036:
                convert << "starting resources set to standard";
                break;
            case -1039:
                convert << "regicide";
                break;
            case -1040:
                convert << "deathmatch";
                break;
            case -70850:
                convert << "one-click garrison";
                break;
            default:
                if (ai_signal >= -518 && ai_signal <= -7) {
                    int signal = ai_signal + 518;
                    int taunt_player = signal / 64;
                    int taunt_set_id = signal % 64;
                    convert << "player " << taunt_player + 1 << " taunted " << taunt_set[taunt_set_id];
                } else if (ai_signal >= -774 && ai_signal <= -519) {
                    convert << "AI goal " << ai_signal + 774 << " achieved";
                } else {
                    convert << "AI signalled " << ai_signal;
                }
            }
            stype.append(convert.str());
            break;
        case ConditionType::ObjectVisible:
            convert << "unit " << object;
            convert << " (" << get_unit_full_name(object) << ") is visible";
            stype.append(convert.str());
            break;
        case ConditionType::PlayerDefeated:
            if (player == 0) {
                convert << "Gaia";
            } else {
                convert << playerPronoun(player);
            }
            convert << " is defeated";
            stype.append(convert.str());
            break;
        case ConditionType::ObjectHasTarget:
            convert << "unit " << object << " (" << get_unit_full_name(object) << ") is targetting";
            if (null_location_unit()) {
                convert << " something";
            } else {
                convert << " " << u_loc << " (" << get_unit_full_name(u_loc) << ")";
            }
            stype.append(convert.str());
            break;
        case ConditionType::UnitsGarrisoned:
            if (amount == 1) {
                convert << "unit " << object << " (" << get_unit_full_name(object) << ") has " << amount << " units garrisoned";
            } else {
                convert << "unit " << object << " (" << get_unit_full_name(object) << ") has one unit garrisoned";
            }
            stype.append(convert.str());
            break;
        case ConditionType::DifficultyLevel:
            convert << "difficulty is ";
            switch (amount) {
            case DifficultyLevel::Hardest:
                convert << "Hardest";
                break;
            case DifficultyLevel::Hard:
                convert << "Hard";
                break;
            case DifficultyLevel::Moderate:
                convert << "Moderate";
                break;
            case DifficultyLevel::Standard:
                convert << "Standard";
                break;
            case DifficultyLevel::Easiest:
                convert << "Easiest";
                break;
            }
            stype.append(convert.str());
            break;
        case ConditionType::UnitsQueuedPastPopCap_SWGB:
            if (valid_player()) {
                convert << playerPronoun(player) << " has " << amount << " units queued past the pop cap";
            } else {
                convert << "INVALID";
            }
            stype.append(convert.str());
            break;
        case ConditionType::OwnFewerFoundations_SWGB: // Chance_HD:
            switch (scen.game) {
            case AOHD:
            case AOF:
            case AOHD4:
            case AOF4:
            case AOHD6:
            case AOF6:
                convert << amount << "% chance ";
                stype.append(convert.str());
                break;
            case SWGB:
            case SWGBCC:
                if (valid_player()) {
                    convert << playerPronoun(player) << " has ";
                }
                if (amount == 0) {
                    convert << "no";
                } else {
                    convert << "at most " << amount;
                }
                if (valid_unit_spec()) {
                    std::string un(wstringToString(pUnit->name()));
                    if (amount > 1 && !un.empty() && *un.rbegin() != 's' && !replaced(un, "man", "men")) {
                        convert << " " << un << " foundations";
                    } else {
                        convert << " " << un << " foundation";
                    }
                } else {
                    if (amount != 1) {
                        convert << " foundations";
                    } else {
                        convert << " foundation";
                    }
                }
                convert << areaName();
                stype.append(convert.str());
                break;
            default:
                convert << amount << "UNKNOWN CONDITION";
                stype.append(convert.str());
            }
            break;
        default:
            stype.append((type < scen.pergame->max_condition_types) ? types_short[type] : "Unknown!");
        }

        return flags&NameFlags::LIMITLEN?stype.substr(0,MAX_CHARS):stype;
    }
}
Ejemplo n.º 11
0
void enumerateTasksForFolder(std::string path, QueryData& results) {
  void* vpService = nullptr;
  auto ret = CoCreateInstance(CLSID_TaskScheduler,
                              nullptr,
                              CLSCTX_INPROC_SERVER,
                              IID_ITaskService,
                              &vpService);
  if (FAILED(ret)) {
    VLOG(1) << "Failed to create COM instance " << ret;
    return;
  }

  auto pService = static_cast<ITaskService*>(vpService);
  ret =
      pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
  if (FAILED(ret)) {
    VLOG(1) << "Failed to connect to TaskService " << ret;
    pService->Release();
    return;
  }

  ITaskFolder* pRootFolder = nullptr;
  auto widePath = stringToWstring(path.c_str());
  ret = pService->GetFolder(BSTR(widePath.c_str()), &pRootFolder);
  pService->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get root task folder " << ret;
    return;
  }

  IRegisteredTaskCollection* pTaskCollection = nullptr;
  ret = pRootFolder->GetTasks(TASK_ENUM_HIDDEN, &pTaskCollection);
  pRootFolder->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get task collection for root folder " << ret;
    return;
  }

  long numTasks = 0;
  pTaskCollection->get_Count(&numTasks);
  for (size_t i = 0; i < numTasks; i++) {
    IRegisteredTask* pRegisteredTask = nullptr;
    // Collections are 1-based lists
    ret = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);
    if (FAILED(ret)) {
      VLOG(1) << "Failed to process task";
      continue;
    }

    Row r;
    BSTR taskName;
    ret = pRegisteredTask->get_Name(&taskName);
    std::wstring wTaskName(taskName, SysStringLen(taskName));
    r["name"] = ret == S_OK ? SQL_TEXT(wstringToString(wTaskName.c_str())) : "";

    VARIANT_BOOL enabled = false;
    pRegisteredTask->get_Enabled(&enabled);
    r["enabled"] = enabled ? INTEGER(1) : INTEGER(0);

    TASK_STATE taskState;
    pRegisteredTask->get_State(&taskState);
    r["state"] = kStateMap.count(taskState) > 0
                     ? kStateMap.at(taskState)
                     : kStateMap.at(TASK_STATE_UNKNOWN);

    BSTR taskPath;
    ret = pRegisteredTask->get_Path(&taskPath);
    std::wstring wTaskPath(taskPath, SysStringLen(taskPath));
    r["path"] = ret == S_OK ? SQL_TEXT(wstringToString(wTaskPath.c_str())) : "";

    VARIANT_BOOL hidden = false;
    pRegisteredTask->get_Enabled(&hidden);
    r["hidden"] = hidden ? INTEGER(1) : INTEGER(0);

    HRESULT lastTaskRun = E_FAIL;
    pRegisteredTask->get_LastTaskResult(&lastTaskRun);
    _com_error err(lastTaskRun);
    r["last_run_message"] = err.ErrorMessage();
    r["last_run_code"] = INTEGER(lastTaskRun);

    // We conver the COM Date type to a unix epoch timestamp
    DATE dRunTime;
    SYSTEMTIME st;
    FILETIME ft;
    FILETIME locFt;

    pRegisteredTask->get_LastRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["last_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    pRegisteredTask->get_NextRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["next_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    results.push_back(r);
    pRegisteredTask->Release();
  }
  pTaskCollection->Release();
}