예제 #1
0
파일: SivDate.cpp 프로젝트: Siv3D/OpenSiv3D
	Date operator +(const Date& date, const Days& days)
	{
		return detail::EpochDaysToDate(detail::DateToEpochDays(date) + days.count());
	}
예제 #2
0
	inline void Formatter(FormatData& formatData, const Days& days)
	{
		Formatter(formatData, days.count());

		formatData.string.push_back(U'd');
	}
예제 #3
0
파일: main.cpp 프로젝트: rhexo/app-lib
int main () {

  auto system_start = chrono::system_clock::now();

  /** Durations */

  chrono::duration<int> twentySeconds(20);  // Базова ЕИ - секунда
  cout << twentySeconds.count() << endl;

  /** Используем рациональные числа, с целью представления значений duration в других ЕИ времени */
  chrono::duration<double,ratio<60>> halfAMinute(0.5);    // 0.5 * ratio<60,1>
  cout << halfAMinute.count() << endl;

  chrono::duration<long,ratio<1,1000>> oneMillisecond(1);
  cout << oneMillisecond.count() << endl;

  // Вывод: 29999 ms
  cout << "diff: " << (halfAMinute - oneMillisecond).count() << " ms" << endl;


  /** По аналогии опредеены и типы пространства имен chrono */
  /** Например: typedef duration<signed int-type>=29 bits, ratio<60>> minutes; */
  chrono::minutes threeHours(180);  // Три часа
  cout << chrono::duration_cast<chrono::hours>(threeHours).count() << "hours" << endl;

  // Выполняем печать с помощью перегруженной функции
  chrono::hours hh = chrono::duration_cast<chrono::hours>(threeHours);
  cout << "180 minutes is = " << hh << endl;

  /** Приведение вещественных значенией интервала */
  chrono::seconds ss = chrono::duration_cast<chrono::seconds>(halfAMinute);
  cout << "half a minute is " << halfAMinute << endl;

  /** Разложение интервала на hh::mm::ss */
  chrono::milliseconds ms(7255101);

  chrono::hours h1 = chrono::duration_cast<chrono::hours>(ms);
  chrono::minutes m1 = chrono::duration_cast<chrono::minutes>(ms % chrono::hours(1));
  chrono::seconds s1 = chrono::duration_cast<chrono::seconds>(ms % chrono::minutes(1));
  chrono::milliseconds ms1 = chrono::duration_cast<chrono::milliseconds>(ms % chrono::seconds(1));

  cout << ms.count() << " ms is " << setfill('0')
       << setw(2) << h1.count() << "::"
       << setw(2) << m1.count() << "::"
       << setw(2) << s1.count() << "::"
       << setw(3) << ms1.count() << endl;



  /** Clocks and timepoints */
  cout << endl;
  cout << "\nsystem_clock: " << endl;
  printClockData<chrono::system_clock>();
  cout << "\nhigh_resolution_clock: " << endl;
  printClockData<chrono::high_resolution_clock>();
  cout << "\nsteady_clock: " << endl;
  printClockData<chrono::steady_clock>();


  // Даем нагрузку
  for (int i = 0; i < 10000000; i++) {
    continue;
  }


  // Время провдолжительности работы программы
  auto diff = chrono::system_clock::now() - system_start;
  auto sec = chrono::duration_cast<chrono::milliseconds>(diff);

  cout << "Program runs: " << sec.count() << " ms" << endl;


  /** Timepoints */

  // Печатаем начало времен для системных часов
  chrono::system_clock::time_point tp;
  cout << "epoch: " << asString(tp) << endl;

  // Печатаем текущее время
  tp = chrono::system_clock::now();
  cout << "now: " << asString(tp) << endl;

  // Печатаем предел слева для часов системного времени
  tp = chrono::system_clock::time_point::min();
  cout << "min: " << asString(tp) << endl;

  // Печатаем предел справа для часов системного времени
  tp = chrono::system_clock::time_point::max();
  cout << "max: " << asString(tp) << endl;

  /** Timepoint arithmetics */

  // Определяем период равный одному дню
  typedef chrono::duration<int,ratio<24*3600>> Days;

  // Определяем значение времени по системным часам
  chrono::time_point<chrono::system_clock> tp_1; // Эквивалентно system_clock::time_point
  cout << "epoch: " << asString(tp_1) << endl;

  // Добавляем один день 23 часа и 55 миут
  tp_1 += Days(1) + chrono::hours(23) + chrono::minutes(55);
  cout << "later: "<< asString(tp_1) << endl;

  // Вычисляем разницу в минутах и днях
  diff = tp_1 - chrono::system_clock::time_point();
  cout << "diff: "
       << chrono::duration_cast<chrono::minutes>(diff).count()
       << " minutes." << endl;
  // Преобразуем относительно введенного нами типа данных
  Days days = chrono::duration_cast<Days>(diff);
  cout << "diff: " << days.count() << "day(s)" << endl;

  // Вычитаем один год (предположительно вычитаемый год является высокосным)
  tp_1 -= chrono::hours(24*365);
  cout << "-1 year: " << asString(tp_1) << endl;

  // Вычисляем 50 лет (утрируем и считаем год равным 365 дням)
  tp_1 -= chrono::duration<int,ratio<3600*24*365>>(50);
  cout << "-50 years: " << asString(tp_1) << endl;

  // Еще раз вычитаем 50 лет
  tp_1 -= chrono::duration<int,ratio<3600*24*365>>(50);
  cout << "-50 years: " << asString(tp_1) << endl;

  /** timepoint/calendar conversion */
  auto tp_m1 = makeTimePoint(2010,01,01,00,00);
  cout << "Make timepoint(1): " << asString(tp_m1) << endl;

  auto tp_m2 = makeTimePoint(2011,05,23,13,44);
  cout << "Make timepoint(2):" << asString(tp_m2) << endl;

  // Добавляем 50 лет к созданной точке времени
  tp_m1 += chrono::duration<int,ratio<3600*24*365>>(50);
  cout << "Add to timepoint(1) 50 years: " << asString(tp_m1) << endl;

  exit(EXIT_SUCCESS);

}
예제 #4
0
bool ProtocolLogin::parseFirstPacket(NetworkMessage& msg)
{
	if(server.game().getGameState() == GAME_STATE_SHUTDOWN)
	{
		getConnection()->close();
		return false;
	}

	uint32_t clientIp = getConnection()->getIP();
	/*uint16_t operatingSystem = msg.GetU16();*/msg.SkipBytes(2);
	uint16_t version = msg.GetU16();

	msg.SkipBytes(12);
	if(!RSA_decrypt(msg))
	{
		getConnection()->close();
		return false;
	}

	uint32_t key[4] = {msg.GetU32(), msg.GetU32(), msg.GetU32(), msg.GetU32()};
	enableXTEAEncryption();
	setXTEAKey(key);

	std::string name = msg.GetString(), password = msg.GetString();
	if(name.empty())
	{
		if(!server.configManager().getBool(ConfigManager::ACCOUNT_MANAGER))
		{
			disconnectClient(0x0A, "Invalid account name.");
			return false;
		}

		name = "1";
		password = "******";
	}

	if(version < CLIENT_VERSION_MIN || version > CLIENT_VERSION_MAX)
	{
		disconnectClient(0x0A, CLIENT_VERSION_STRING);
		return false;
	}

	if(server.game().getGameState() < GAME_STATE_NORMAL)
	{
		disconnectClient(0x0A, "Server is just starting up, please wait.");
		return false;
	}

	if(server.game().getGameState() == GAME_STATE_MAINTAIN)
	{
		disconnectClient(0x0A, "Server is under maintenance, please re-connect in a while.");
		return false;
	}

	if(ConnectionManager::getInstance()->isDisabled(clientIp, protocolId))
	{
		disconnectClient(0x0A, "Too many connections attempts from your IP address, please try again later.");
		return false;
	}

	if(IOBan::getInstance()->isIpBanished(clientIp))
	{
		disconnectClient(0x0A, "Your IP is banished!");
		return false;
	}

	uint32_t id = 1;
	if(!IOLoginData::getInstance()->getAccountId(name, id))
	{
		ConnectionManager::getInstance()->addAttempt(clientIp, protocolId, false);
		disconnectClient(0x0A, "Invalid account name.");
		return false;
	}

	AccountP account = IOLoginData::getInstance()->loadAccount(id);
	if (account == nullptr) {
		disconnectClient(0x0A, "Invalid account name.");
		return false;
	}

	if(!encryptTest(password, account->getPassword()))
	{
		ConnectionManager::getInstance()->addAttempt(clientIp, protocolId, false);
		disconnectClient(0x0A, "Invalid password.");
		return false;
	}

	Ban ban;
	ban.value = account->getId();

	ban.type = BAN_ACCOUNT;
	if(IOBan::getInstance()->getData(ban) && !IOLoginData::getInstance()->hasFlag(account->getId(), PlayerFlag_CannotBeBanned))
	{
		bool deletion = ban.expires < 0;
		std::string name_ = "Automatic ";
		if(!ban.adminId)
			name_ += (deletion ? "deletion" : "banishment");
		else
			IOLoginData::getInstance()->getNameByGuid(ban.adminId, name_, true);

		char buffer[500 + ban.comment.length()];
		sprintf(buffer, "Your account has been %s at:\n%s by: %s,\nfor the following reason:\n%s.\nThe action taken was:\n%s.\nThe comment given was:\n%s.\nYour %s%s.",
			(deletion ? "deleted" : "banished"), formatDateShort(ban.added).c_str(), name_.c_str(),
			getReason(ban.reason).c_str(), getAction(ban.action, false).c_str(), ban.comment.c_str(),
			(deletion ? "account won't be undeleted" : "banishment will be lifted at:\n"),
			(deletion ? "." : formatDateShort(ban.expires, true).c_str()));

		disconnectClient(0x0A, buffer);
		return false;
	}

	const Account::Characters& characters = account->getCharacters();
	if(!server.configManager().getBool(ConfigManager::ACCOUNT_MANAGER) && characters.empty())
	{
		disconnectClient(0x0A, std::string("This account does not contain any character yet.\nCreate a new character on the "
			+ server.configManager().getString(ConfigManager::SERVER_NAME) + " website at " + server.configManager().getString(ConfigManager::URL) + ".").c_str());
		return false;
	}

	ConnectionManager::getInstance()->addAttempt(clientIp, protocolId, true);
	if(OutputMessage_ptr output = OutputMessagePool::getInstance()->getOutputMessage(this, false))
	{
		TRACK_MESSAGE(output);
		output->AddByte(0x14);

		char motd[1300];
		sprintf(motd, "%d\n%s", server.game().getMotdId(), server.configManager().getString(ConfigManager::MOTD).c_str());
		output->AddString(motd);

		uint32_t serverIp = serverIps[0].first;
		for(IpList::iterator it = serverIps.begin(); it != serverIps.end(); ++it)
		{
			if((it->first & it->second) != (clientIp & it->second))
				continue;

			serverIp = it->first;
			break;
		}

		//Add char list
		output->AddByte(0x64);
		if(server.configManager().getBool(ConfigManager::ACCOUNT_MANAGER) && id != 1)
		{
			output->AddByte(characters.size() + 1);
			output->AddString("Account Manager");
			output->AddString(server.configManager().getString(ConfigManager::SERVER_NAME));
			output->AddU32(serverIp);
			output->AddU16(server.configManager().getNumber(ConfigManager::GAME_PORT));
		}
		else
			output->AddByte((uint8_t)characters.size());

		for (auto it = characters.cbegin(); it != characters.cend(); ++it) {
			auto& character = *it;

#ifndef __LOGIN_SERVER__
			output->AddString(character->getName());
			output->AddString(character->getType());
			output->AddU32(serverIp);
			output->AddU16(server.configManager().getNumber(ConfigManager::GAME_PORT));
#else
			if(version < it->second->getVersionMin() || version > it->second->getVersionMax())
				continue;

			output->AddString(it->first);
			output->AddString(it->second->getName());
			output->AddU32(it->second->getAddress());
			output->AddU16(it->second->getPort());
#endif
		}

		Days premiumDays = account->getPremiumDays();
		if (premiumDays.count() >= std::numeric_limits<uint16_t>::max()) {
			output->AddU16(std::numeric_limits<uint16_t>::max());
		}
		else {
			output->AddU16(static_cast<uint16_t>(premiumDays.count()));
		}

		OutputMessagePool::getInstance()->send(output);
	}

	getConnection()->close();
	return true;
}