Esempio n. 1
0
	void SendList()
	{
		TFavContacts favList;
		favList.build();

		m_socket->Send(
			"HTTP 200 OK\r\n"
			"Content-Type: text/javascript\r\n"
			"\r\n");

		Send("try {\r\n");
		Send("SetContactCount(");
		Send(favList.getCount());
		Send(");\r\n");

		for (int i = 0; i < favList.getCount(); ++i)
		{
			MCONTACT hContact = favList[i]->getHandle();
			TCHAR *name = (TCHAR *)pcli->pfnGetContactDisplayName(hContact, 0);
			AVATARCACHEENTRY *avatar = (AVATARCACHEENTRY *)CallService(MS_AV_GETAVATARBITMAP, hContact, 0);
			int status = db_get_w(hContact, GetContactProto(hContact), "Status", ID_STATUS_OFFLINE);

			Send("SetContact(");
			Send(i);
			Send(", ");
			Send((int)hContact);// XXX: x64 broken!?
			Send(", '");
			SendQuoted(name);
			Send("', ");
			Send(status);
			Send(", '");
			SendQuoted(avatar ? avatar->szFilename : _T(""));
			Send("');\r\n");
		}
		Send("} catch(e) {}\r\n");
	}
Esempio n. 2
0
	/// <summary>
	/// Sends the specified buf.
	/// </summary>
	/// <param name="buf">需要发送数据的指针.</param>
	/// <param name="nLength">发送消息的长度.</param>
	/// <param name="callback">本次发送是否需要设置发送完成的回调.</param>
	void TcpConnection::Send( char* buf, uint32_t nLength,bool callback)
	{
		string msg(buf,nLength);
		Send( msg ,callback);
	}
Esempio n. 3
0
/*
 * - Send_Int() - uses Send() to send one int
 */
void Send_Int(int connfd, uint32_t val){
    Send(connfd, &val, sizeof(val));
    //return return_value;
    //return ntohl(return_value);
}
Esempio n. 4
0
// sungyong 2002.05.22
void CGameSocket::RecvServerConnect(char *pBuf)
{
    int index = 1;
    int outindex = 0, zone_index = 0;
    float fReConnectEndTime = 0.0f;
    char pData[1024];
    BYTE byZoneNumber = GetByte(pBuf, index);
    BYTE byReConnect = GetByte(pBuf, index);	// 0 : 처음접속, 1 : 재접속

    CString logstr;
    logstr.Format("[GameServer Connect - %d]", byZoneNumber);
    m_pMain->m_StatusList.AddString( logstr );
    TRACE(logstr);

    if(byZoneNumber < 0)		{
        SetByte(pData, SERVER_CONNECT, outindex);
        SetByte(pData, -1, outindex);
        Send(pData, outindex);
    }

    m_sSocketID = byZoneNumber;

    SetByte(pData, SERVER_CONNECT, outindex);
    SetByte(pData, byZoneNumber, outindex);
    SetByte(pData, byReConnect, outindex);
    Send(pData, outindex);

    if(byReConnect == 1)	{	// 재접속해서 리스트 받기 (강제로)
        if(m_pMain->m_sReSocketCount == 0)
            m_pMain->m_fReConnectStart = TimeGet();
        m_pMain->m_sReSocketCount++;
        TRACE("**** ReConnect - zone=%d,  socket = %d ****\n ", byZoneNumber, m_pMain->m_sReSocketCount);
        fReConnectEndTime = TimeGet();
        if(fReConnectEndTime > m_pMain->m_fReConnectStart+120)	{	// 2분안에 모든 소켓이 재접됐다면...
            TRACE("**** ReConnect - 단순한 접속... socket = %d ****\n ", m_pMain->m_sReSocketCount);
            m_pMain->m_sReSocketCount = 0;
            m_pMain->m_fReConnectStart = 0.0f;
        }

        if(m_pMain->m_sReSocketCount == MAX_AI_SOCKET)	{
            fReConnectEndTime = TimeGet();
            if(fReConnectEndTime < m_pMain->m_fReConnectStart+60)	{	// 1분안에 모든 소켓이 재접됐다면...
                TRACE("**** ReConnect - 모든 소켓 초기화 완료 socket = %d ****\n ", m_pMain->m_sReSocketCount);
                m_pMain->m_bFirstServerFlag = TRUE;
                m_pMain->m_sReSocketCount = 0;
                m_pMain->AllNpcInfo();
            }
            else	{								// 하나의 떨어진 소켓이라면...
                m_pMain->m_sReSocketCount = 0;
                m_pMain->m_fReConnectStart = 0.0f;
            }
        }
    }
    else	{
        //m_pMain->PostMessage( WM_GAMESERVER_LOGIN, (LONG)byZoneNumber );
        m_pMain->m_sSocketCount++;
        TRACE("**** Connect - zone=%d,  socket = %d ****\n ", byZoneNumber, m_pMain->m_sSocketCount);
        if(m_pMain->m_sSocketCount == MAX_AI_SOCKET)	{
            TRACE("**** Connect - 모든 소켓 초기화 완료 socket = %d ****\n ", m_pMain->m_sSocketCount);
            m_pMain->m_bFirstServerFlag = TRUE;
            m_pMain->m_sSocketCount = 0;
            m_pMain->AllNpcInfo();
        }
    }
}
Esempio n. 5
0
void CUser::Regene(uint8 regene_type, uint32 magicid /*= 0*/)
{
	ASSERT(GetMap() != nullptr);

	_OBJECT_EVENT* pEvent = nullptr;
	_HOME_INFO* pHomeInfo = nullptr;
	float x = 0.0f, z = 0.0f;

	if (!isDead())
		return;

	if (regene_type != 1 && regene_type != 2)
		regene_type = 1;

	if (regene_type == 2) 
	{
		magicid = 490041;	// The Stone of Ressurection magic ID

		// Is our level high enough to be able to resurrect using this skill?
		if (GetLevel() <= 5
			// Do we have enough resurrection stones?
				|| !RobItem(379006000, 3 * GetLevel()))
				return;
	}

	// If we're in a home zone, we'll want the coordinates from there. Otherwise, assume our own home zone.
	pHomeInfo = g_pMain->m_HomeArray.GetData(GetZoneID() <= ZONE_ELMORAD ? GetZoneID() : GetNation());
	if (pHomeInfo == nullptr)
		return;

	UserInOut(INOUT_OUT);

	pEvent = GetMap()->GetObjectEvent(m_sBind);	

	// If we're not using a spell to resurrect.
	if (magicid == 0) 
	{
		// Resurrect at a bind/respawn point
		if (pEvent != nullptr && pEvent->byLife == 1)
		{
			SetPosition(pEvent->fPosX + x, 0.0f, pEvent->fPosZ + z);
		}
		// Are we trying to respawn in a home zone?
		else if (GetZoneID() <= ZONE_ELMORAD) 
		{
			// Use the proper respawn area for our nation, as the opposite nation can
			// enter this zone at a war's invasion stage.
			if (GetNation() == KARUS) 
			{
				x = (float)(pHomeInfo->KarusZoneX + myrand(0, pHomeInfo->KarusZoneLX));
				z = (float)(pHomeInfo->KarusZoneZ + myrand(0, pHomeInfo->KarusZoneLZ));			
			}
			else 
			{
				x = (float)(pHomeInfo->ElmoZoneX + myrand(0, pHomeInfo->ElmoZoneLX));
				z = (float)(pHomeInfo->ElmoZoneZ + myrand(0, pHomeInfo->ElmoZoneLZ));
			}		
		}
		else
		{
			// If we're in a war zone (aside from snow wars, which apparently use different coords), use BattleZone coordinates.
			if (GetZoneID() != ZONE_SNOW_BATTLE 
				&& GetZoneID() == (ZONE_BATTLE_BASE + g_pMain->m_byBattleZone))
			{
				x = (float)(pHomeInfo->BattleZoneX + myrand(0, pHomeInfo->BattleZoneLX));
				z = (float)(pHomeInfo->BattleZoneZ + myrand(0, pHomeInfo->BattleZoneLZ));
			}
			// If we died in the Moradon arena, we need to spawn near the Arena.
			else if (GetZoneID() == ZONE_MORADON && isInArena())
			{
				x = (float)(MINI_ARENA_RESPAWN_X + myrand(-MINI_ARENA_RESPAWN_RADIUS, MINI_ARENA_RESPAWN_RADIUS));
				z = (float)(MINI_ARENA_RESPAWN_Z + myrand(-MINI_ARENA_RESPAWN_RADIUS, MINI_ARENA_RESPAWN_RADIUS));
			}
			// For all else, just grab the start position (/town coordinates) from the START_POSITION table.
			else
			{
				short sx, sz;
				GetStartPosition(sx, sz);

				x = sx;
				z = sz;
			}
		}

		SetPosition(x, 0.0f, z);

		m_bResHpType = USER_STANDING;	
		m_bRegeneType = REGENE_NORMAL;
	}
	else // we're respawning using a resurrect skill.
	{
		_MAGIC_TYPE5 * pType = g_pMain->m_Magictype5Array.GetData(magicid);     
		if (pType == nullptr)
			return;

		MSpChange(-m_iMaxMp); // reset us to 0 MP. 

		if (m_sWhoKilledMe == -1) 
			ExpChange((m_iLostExp * pType->bExpRecover) / 100); // Restore 

		m_bResHpType = USER_STANDING;
		m_bRegeneType = REGENE_MAGIC;
	}

	Packet result(WIZ_REGENE);
	result << GetSPosX() << GetSPosZ() << GetSPosY();
	Send(&result);

	HpChange(GetMaxHealth());

	m_tLastRegeneTime = UNIXTIME;
	m_sWhoKilledMe = -1;
	m_iLostExp = 0;

	if (magicid == 0)
		BlinkStart();

	if (!isBlinking())
	{
		result.Initialize(AG_USER_REGENE);
		result << GetSocketID() << m_sHp;
		Send_AIServer(&result);
	}

	SetRegion(GetNewRegionX(), GetNewRegionZ());

	UserInOut(INOUT_RESPAWN);		

	g_pMain->RegionUserInOutForMe(this);
	g_pMain->RegionNpcInfoForMe(this);

	InitializeStealth();
	SendUserStatusUpdate(USER_STATUS_DOT, USER_STATUS_CURE);
	SendUserStatusUpdate(USER_STATUS_POISON, USER_STATUS_CURE);

	if (isInArena())
		SendUserStatusUpdate(USER_STATUS_SPEED, USER_STATUS_CURE);

	RecastSavedMagic();

	// If we actually respawned (i.e. we weren't resurrected by a skill)...
	if (magicid == 0)
	{
		// In PVP zones (not war zones), we must kick out players if they no longer
		// have any national points.
		if (GetMap()->isNationPVPZone() 
			&& GetMap()->isWarZone()
			&& GetLoyalty() == 0)
			KickOutZoneUser(false);
	}
}
Esempio n. 6
0
status_t MSNConnection::HandleUSR( Command * command ) {
	LOG(kProtocolName, liDebug, "C %lX: Processing USR", this);
	status_t result = B_ERROR;

	if (strcmp(command->Param(0), "OK") == 0) {
		Progress("MSN Login", "MSN: Logged in!", 1.0);
		
		GoOnline();
		
		BMessage statusChange(msnmsgOurStatusChanged);
		statusChange.AddInt8("status", fState);
		fManMsgr.SendMessage(&statusChange);

		/*
		 * Depending on the server protocol, server location and the
		 * account being used (non-hotmail/msn acc), the server will not
		 * respond on the PRP MFN command and our connection will break.
		 * Michael
		 */
		BString passport(fManager->Passport());
		
		if ((B_ERROR != passport.FindFirst("@hotmail")) || (B_ERROR != passport.FindFirst("@msn"))) {
			LOG(kProtocolName, liDebug, "Sending PRP MSN command" );
			
			Command *rea = new Command("PRP");
			rea->AddParam("MFN");
			rea->AddParam(fManager->DisplayName(), true);
			Send(rea);
		} else {
			LOG(kProtocolName, liDebug, "Not sending PRP MSN command!");
		};
		
		fManager->Handler()->ContactList(&fContacts);
				
		Command *adl = new Command("ADL");
		
		std::list<BString> contacts;
		std::map<BString, std::list<BString> > domainUsers;
		
		fManager->Handler()->ContactList(&contacts);
		
		// Make our contact list into a list by domain
		for (std::list<BString>::iterator iIt = contacts.begin(); iIt != contacts.end(); iIt++) {
			BString user;
			BString domain;
			
			if (SplitEmail((*iIt).String(), user, domain) == B_OK) {			
				std::map<BString, std::list<BString> >::iterator dIt = domainUsers.find(domain);
				if (dIt == domainUsers.end()) {
					std::list<BString> users;
					users.push_back(user);
					
					domainUsers[domain] = users;
				} else {
					dIt->second.push_back(user);
				};
			};
		};

		BString payload = "<ml l=\"1\">";

		// Package each contact by domain
		for (std::map<BString, std::list<BString> >::iterator dIt = domainUsers.begin(); dIt != domainUsers.end(); dIt++) {
			payload << "<d n=\"" << dIt->first << "\">";
		
			for (std::list<BString>::iterator uIt = dIt->second.begin(); uIt != dIt->second.end(); uIt++) {
				payload << "<c n=\"" << (*uIt) <<  "\" l=\"3\" t=\"1\" />";
			};
			
			payload << "</d>";
		};
		
		payload << "</ml>";
		adl->AddPayload(payload.String());
		
		Send(adl);
		
		Command *chg = new Command("CHG");
		chg->AddParam("NLN");
		BString caps = "";
		caps << kOurCaps;
		chg->AddParam( caps.String() );
		Send(chg);

		result = B_OK;
	} else {
		BString URI = command->Param(2);
		BString nonce = command->Param(3);
		BString authResp = "";
		BString authToken = "";

		SSO *auth = new SSO(NULL, fManager->Passport(), fManager->Password(), URI.String(),
			nonce.String());

		result = auth->Response(authToken, authResp);

		if (result == B_OK) {
			Command *reply = new Command("USR");
			reply->AddParam("SSO");
			reply->AddParam("S");
			reply->AddParam(authToken.String());
			reply->AddParam(authResp.String());
			
			reply->Debug();
			
			Send(reply);
		};

	};
	
	return result;
}
Esempio n. 7
0
void PrintSchdFile(Record* const rd, int index) {
  FILE *fp;
  if (index == 1) {
    fp = fopen("FCFS_Schd.dat", "a");
  }
  else if (index == 2) {
    fp = fopen("PRIO_Schd.dat", "a");
  }
  else {
    fp = fopen("OPTI_Schd.dat", "a");
  }
  Record* cur = rd;
  int rejected_a = 0;
  int rejected_b = 0;
  int rejected_d = 0;
  int total = 0;
  int i;
  char message_from_child[2];

  //Accepted Part
  fprintf(fp, " ____________________________________________________________________________ \n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|***Room Booking - ACCEPTED***                                               |\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Room_A has the following bookings:                                          |\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Date         Start   End     Type          Requester  Device                |\n");
  fprintf(fp, "|============================================================================|\n");

  while (cur->next != NULL) {
    cur = cur->next;
    total++;
    if (cur->room_A == 1 && cur->accept == 1)
      PrintAccept(cur, fp);
    else if (cur->room_A == 1)
      rejected_a++;
  }

  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Room_B has the following bookings:                                          |\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Date         Start   End     Type          Requester  Device                |\n");
  fprintf(fp, "|============================================================================|\n");

  cur = rd;
  while (cur->next != NULL) {
    cur = cur->next;
    if (cur->room_B == 1 && cur->accept == 1)
      PrintAccept(cur, fp);
    else if (cur->room_B == 1)
      rejected_b++;
  }

  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|   -End-                                                                    |\n");
  fprintf(fp, "|============================================================================|\n");
  fprintf(fp, "|____________________________________________________________________________|\n");

  //Rejected Part
  fprintf(fp, " ____________________________________________________________________________ \n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|***Room Booking - REJECTED***                                               |\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Room_A, there are %d bookings rejected.                                      ", rejected_a);
  Format(fp, rejected_a);
  fprintf(fp, "|\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Date         Start   End     Type          Device                           |\n");
  fprintf(fp, "|============================================================================|\n");

  cur = rd;
  while (cur->next != NULL) {
    cur = cur->next;
    if (cur->room_A == 1 && cur->accept == 0) PrintReject(cur, fp);
  }

  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Room_B, there are %d bookings rejected.                                      ", rejected_b);
  Format(fp, rejected_b);
  fprintf(fp, "|\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Date         Start   End     Type          Device                           |\n");
  fprintf(fp, "|============================================================================|\n");

  cur = rd;
  while (cur->next != NULL) {
    cur = cur->next;
    if (cur->room_B == 1 && cur->accept == 0)
      PrintReject(cur, fp);
  }

  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|   -End-                                                                    |\n");
  fprintf(fp, "|============================================================================|\n");
  fprintf(fp, "|____________________________________________________________________________|\n");

  cur = rd;
  while (cur->next != NULL) {
    cur = cur->next;
    if (cur->type == 0 && cur->accept == 0)
      rejected_d++;
  }

  //Performance part
  fprintf(fp, " ____________________________________________________________________________ \n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Performance:                                                                |\n");
  fprintf(fp, "|                                                                            |\n");
  fprintf(fp, "|Total Number of Bookings Received: %d (100.0%%)                               ", total);
  Format(fp, total);
  fprintf(fp, "|\n");
  fprintf(fp, "|      Number of Bookings Assigned: %d (%.1f%%)                                 ", total - rejected_a - rejected_b - rejected_d, total == 0 ? 0.0 : (double) (total - rejected_a - rejected_b - rejected_d) * 100.0 / (double) total);
  Format(fp, total - rejected_a - rejected_b - rejected_d);
  Format(fp, total == 0 ? 0.0 : (double) (total - rejected_a - rejected_b - rejected_d) * 100.0 / (double) total);
  fprintf(fp, "|\n");
  fprintf(fp, "|      Number of Bookings Rejected: %d (%.1f%%)                                 ", rejected_a + rejected_b + rejected_d, total == 0 ? 0.0 : (double) (rejected_a + rejected_b + rejected_d) * 100.0 / (double) (total));
  Format(fp, rejected_a + rejected_b + rejected_d);
  Format(fp, total == 0 ? 0.0 : (double) (rejected_a + rejected_b + rejected_d) * 100.0 / (double) (total));
  fprintf(fp, "|\n");
  fprintf(fp, "|Utilization of Time Slot:                                                   |\n");
  fprintf(fp, "|                                                                            |\n");

  for (i = 0; i < 10; i++) {
    time_slot_record[i] = Send(i, "00T");
  }

  fprintf(fp, "|      Room_A                  - %.1f%%                                        ", (double) time_slot_record[0] * 100.0 / 126.0);
  Format(fp,time_slot_record[0] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      Room_B                  - %.1f%%                                        ", (double) time_slot_record[1] * 100.0 / 126.0);
  Format(fp, time_slot_record[1] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      webcam_720p             - %.1f%%                                        ", (double) time_slot_record[2] * 100.0 / 126.0);
  Format(fp, time_slot_record[2] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      webcam_1080p            - %.1f%%                                        ", (double) time_slot_record[3] * 100.0 / 126.0);
  Format(fp, time_slot_record[3] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      monitor_50              - %.1f%%                                        ", (double) time_slot_record[4] * 100.0 / 126.0);
  Format(fp, time_slot_record[4] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      monitor_75              - %.1f%%                                        ", (double) time_slot_record[5] * 100.0 / 126.0);
  Format(fp, time_slot_record[5] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      projector_fhd           - %.1f%%                                        ", (double) time_slot_record[6] * 100.0 / 126.0);
  Format(fp, time_slot_record[6] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      projector_xga           - %.1f%%                                        ", (double) time_slot_record[7] * 100.0 / 126.0);
  Format(fp, time_slot_record[7] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      screen_100              - %.1f%%                                        ", (double) time_slot_record[8] * 100.0 / 126.0);
  Format(fp, time_slot_record[8] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|      screen_150              - %.1f%%                                        ", (double) time_slot_record[9] * 100.0 / 126.0);
  Format(fp, time_slot_record[9] * 100 / 126);
  fprintf(fp, "|\n");

  fprintf(fp, "|____________________________________________________________________________|\n");
}
Esempio n. 8
0
static void decodeCommand() {
  decoderBuffer[decoderCurrBufferPos] = 0;
  if (decoderCurrBufferPos == 1 && decoderBuffer[0] == 'q') {
    kernel_quit();
  }
  unsigned int shortEvalulation = (decoderCurrBufferPos <= 1);
  decoderCurrBufferPos = 0;
  if (shortEvalulation) return;

  PrintDebug(ui, "__Command: %s", decoderBuffer);
  if (decoderBuffer[0] == 'b' && decoderBuffer[1] == 'a') {
    // Bait command
    char *temp = (char *)decoderBuffer + 5;
    int train_number = strgetui(&temp);

    DoBaitPositionFinding(trainController, train_number);
    int ret = RegisterBait(snakeDirector, train_number);

  } else if (decoderBuffer[0] == 's' && decoderBuffer[2] == 'a') {
    // Snake command
    char *temp = (char*)decoderBuffer + 6;
    int train_number = strgetui(&temp);

    DoPositionFinding(trainController, train_number);
    int ret = RegisterSnake(snakeDirector, train_number);
  } else if (decoderBuffer[0] == 'i' && decoderBuffer[1] == 'n') {
    char *temp = (char *)decoderBuffer + 5;
    int train_number = strgetui(&temp);
    DoPositionFinding(trainController, train_number);
  } else if (decoderBuffer[0] == 't' && decoderBuffer[1] == 's') {
    char *temp = (char*)decoderBuffer + 3;

    char letter = *temp++;
    int num = strgetui(&temp);
    if (letter >= 'a' && letter <= 'e') {
      letter = letter - 'a' + 'A';
    }
    if (letter >= 'A' && letter <= 'E' && num >= 1 && num <= 16) {
      triggerFakeSensor(sensorServer, Time(timeServer), letter-'A', (char)num);
    } else {
      PrintDebug(ui, "Invalid Fake Sensor Value");
    }
  }  else if (decoderBuffer[0] == 'u' && decoderBuffer[1] == 's') {
    char *temp = (char *)decoderBuffer + 3;
    char track = *temp++;

    TrackMsg msg;
    msg.type = SET_TRACK;
    if (track == 'a' || track == 'b') {
      msg.data =track;
      Send(trackController, (char *)&msg, sizeof(TrackMsg), (char *)1, 0);
    }
  } else if (decoderBuffer[0] == 't' && decoderBuffer[1] == 'r') {
    char *temp = (char *)decoderBuffer + 3;
    int train_number = strgetui(&temp);
    temp++;
    int train_speed = strgetui(&temp);
    temp++;

    SetSpeedTrain(trainController, train_number, train_speed);
  } else if (decoderBuffer[0] == 'r' && decoderBuffer[1] == 'v') {
    char *temp = (char *)decoderBuffer + 3;
    int train_number = strgetui(&temp);
    ReverseTrain(trainController, train_number);
  } else if (decoderBuffer[0] == 's' && decoderBuffer[1] == 'w') {
    char *temp = (char *)decoderBuffer + 3;
    int switch_number = strgetui(&temp);
    temp++;

    char switch_pos = *temp++;
    if (switch_pos == 's' || switch_pos == 'c') {
      TrackMsg setSwitch;

      TrackLandmark sw;
      sw.type = LANDMARK_SWITCH;
      sw.num1 = 0;
      sw.num2 = (char)switch_number;

      setSwitch.type = SUDO_SET_SWITCH;
      setSwitch.landmark1 = sw;
      setSwitch.data = switch_pos == 'c' ? SWITCH_CURVED : SWITCH_STRAIGHT;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);

      DriverMsg trainMsg;
      trainMsg.trainNum = 255;
      trainMsg.type = BROADCAST_UPDATE_PREDICTION;
      Send(trainController, (char*)&trainMsg, sizeof(trainMsg), (char *)NULL, 0);
    }
  } else if (decoderBuffer[0] == 'r' && decoderBuffer[1] == 'o') {
    char *temp = (char *)decoderBuffer + 3;

    int train_number = strgetui(&temp);
    temp++;
    int train_speed = 9;
    if (*temp >= '0' && *temp <= '9'){
      train_speed = strgetui(&temp);
      temp++;
    }

    char letter;
    int num;

    Position pos;

    letter = *temp++;
    num = strgetui(&temp);
    temp++;
    pos.landmark1 = formLandmarkFromInput(letter, num);

    letter = *temp++;
    num = strgetui(&temp);
    temp++;
    pos.landmark2 = formLandmarkFromInput(letter, num);

    pos.offset = 0;
    if (*temp >= '0' && *temp <= '9'){
      pos.offset = strgetui(&temp);
    }

    DriverMsg msg;
    msg.trainNum = train_number;
    msg.type  = SET_ROUTE;
    msg.data2 = train_speed;
    msg.pos = pos;
    PrintDebug(ui, "CD: Route %d %d %d %d %d %d %d %d %d",
        train_number, train_speed,
        pos.landmark1.type, pos.landmark1.num1, pos.landmark1.num2,
        pos.landmark2.type, pos.landmark2.num1, pos.landmark2.num2,
        pos.offset);

    if (pos.landmark1.type == LANDMARK_FAKE ||
        pos.landmark2.type == LANDMARK_FAKE) {
      PrintDebug(ui, "Parse Fail: %s", decoderBuffer);
    } else {
      Send(trainController, (char *)&msg, sizeof(DriverMsg), (char *)NULL, 0);
    }
  } else if (decoderBuffer[0] == 'r' && decoderBuffer[1] == 's') {
    char *temp = (char*)decoderBuffer + 3;

    int train_number = strgetui(&temp);
    TrackMsg msg;
    msg.type = QUERY_EDGES_RESERVED;
    msg.data = (char)train_number;
    Send(trackController, (char *)&msg, sizeof(TrackMsg), (char *)1, 0);
  } else if (decoderBuffer[0] == 'x' && decoderBuffer[1] == 'x') {
    char *temp = (char*)decoderBuffer + 3;
    int train_number = strgetui(&temp);
    Send(randomController, (char*)&train_number, 4, (char *)1, 0);
  } else if (decoderBuffer[0] == 't' && decoderBuffer[1] == 'm') {
    int train_number = 255;
    PrintDebug(ui, "Trains going in test mode");
    PrintDebug(ui, "Make sure smaller numbered train is at A4, larger numbered train at D6");
    DriverMsg msg;
    msg.type = BROADCAST_TEST_MODE;
    msg.trainNum = 255;
    msg.data2 = 8;
    Send(trainController, (char *)&msg, sizeof(DriverMsg), (char *)NULL, 0);
  } else if (decoderBuffer[0] == 'm' && decoderBuffer[1] == 'r') {
    char *temp = (char *)decoderBuffer + 3;
    int train_number1 = strgetui(&temp);
    temp++;
    int train_number2 = strgetui(&temp);
    temp++;

    // Train1 is head, train2 is new tail
    DoTrainMerge(trainController, train_number1, train_number2);
  } else if (decoderBuffer[0] == 'q' && decoderBuffer[1] == 'd') {
    char *temp = (char *)decoderBuffer + 3;

    char letter, num;
    letter = *temp++;
    Position pos;
    num = strgetui(&temp);
    temp++;
    pos.landmark1 = formLandmarkFromInput(letter, num);

    letter = *temp++;
    num = strgetui(&temp);
    temp++;
    pos.landmark2 = formLandmarkFromInput(letter, num);
    pos.offset = 1;

    letter = *temp++;
    Position pos2;
    num = strgetui(&temp);
    temp++;
    pos2.landmark1 = formLandmarkFromInput(letter, num);

    letter = *temp++;
    num = strgetui(&temp);
    temp++;
    pos2.landmark2 = formLandmarkFromInput(letter, num);
    pos2.offset = 2;

    int distance = 9999;
    QueryDistance(trackController, &pos, &pos2, &distance);
    PrintDebug(ui, "Distance: %d", distance);
  } else if (decoderBuffer[0] == 'p' && decoderBuffer[1] == 'r') {
    DoPositionFinding(trainController, 45);
    Delay(80, timeServer);
    triggerFakeSensor(sensorServer, Time(timeServer), 3, 6); // D6
    DoPositionFinding(trainController, 44);
    Delay(80, timeServer);
    triggerFakeSensor(sensorServer, Time(timeServer), 4, 5); // E5
    DoPositionFinding(trainController, 43);
    Delay(40, timeServer);
    triggerFakeSensor(sensorServer, Time(timeServer), 3, 3); // D3
    DoTrainMerge(trainController, 45, 44);
    DoTrainMerge(trainController, 45, 43);
    Delay(40, timeServer);
    SetSpeedTrain(trainController, 45, 5);
    Delay(40, timeServer);
    // Train 44 moves
    triggerFakeSensor(sensorServer, Time(timeServer), 3, 6);  // D6
    Delay(40, timeServer);
    // Train 45 moves
    triggerFakeSensor(sensorServer, Time(timeServer), 4, 10); // E10
    Delay(40, timeServer);
    PrintDebug(ui, "e13");
    // Train 45 moves
    triggerFakeSensor(sensorServer, Time(timeServer), 4, 13); // E13
    Delay(40, timeServer);
    PrintDebug(ui, "last d6 ");
    // Train 43 moves
    triggerFakeSensor(sensorServer, Time(timeServer), 3, 6);  // D6
    Delay(40, timeServer);
  } else if (decoderBuffer[0] == 'f' && decoderBuffer[1] == 'o') {
    // sets the max/min distance between train during merge mode
    char *temp = (char *)decoderBuffer + 3;
    int train_number = strgetui(&temp);
    temp++;
    int min_dist = strgetui(&temp);
    temp++;
    int max_dist = strgetui(&temp);
    temp++;

    if (max_dist > min_dist) {
      SetFollowingDistance(trainController, train_number, min_dist, max_dist);
    } else {
      PrintDebug(ui, "ERROR, maxDist less than minDist");
    }
  } else if (decoderBuffer[0] == 'b' && decoderBuffer[1] == 'i' && decoderBuffer[2] == 'g') {
      TrackMsg setSwitch;
      setSwitch.type = SUDO_SET_SWITCH;
      setSwitch.landmark1.type = LANDMARK_SWITCH;
      setSwitch.landmark1.num1 = 0;

      setSwitch.data = SWITCH_CURVED;
      setSwitch.landmark1.num2 = 8;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 9;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 14;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 15;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);

      setSwitch.data = SWITCH_STRAIGHT;
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 10;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 13;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 16;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);
      Delay(1, timeServer);
      setSwitch.landmark1.num2 = 17;
      Send(trackController, (char*)&setSwitch, sizeof(TrackMsg), (char *)NULL, 0);

      DriverMsg trainMsg;
      trainMsg.trainNum = 255;
      trainMsg.type = BROADCAST_UPDATE_PREDICTION;
      Send(trainController, (char*)&trainMsg, sizeof(trainMsg), (char *)NULL, 0);


  } else {
    PrintDebug(ui, "__Bad command__ %s", decoderBuffer);
    return;
  }
}
Esempio n. 9
0
//======================================================================================
// HandleCreatePlayerMsg()
//
// Handles create player system message from DPlay.
//======================================================================================
void CDarkPeer::HandleCreatePlayerMsg(DPNMSG_CREATE_PLAYER* pCreatePlayer)
{
	csReceive.Lock(); // Block packet receives while we're handling this

	// Translate DPlay8's create player message to DPlay4
	char playerName[kMaxPlayerName] = "";
	DPMSG_CREATEPLAYERORGROUP* pDP4CreatePlayer = new DPMSG_CREATEPLAYERORGROUP;

	// Retrieve the peer info and set the host and local DPNIDs
	DPN_PLAYER_INFO* pdpPlayerInfo = GetPeerInfo(pCreatePlayer->dpnidPlayer);

	//Log.Print("Connection from DPNID: %08x", pCreatePlayer->dpnidPlayer);

	if (pdpPlayerInfo)
	{
		if (pdpPlayerInfo->dwPlayerFlags == DPNPLAYER_HOST)
		{
			m_dpnidHost = pCreatePlayer->dpnidPlayer;

			if (Debug.IsFlagSet(DEBUG_NET))
				ConPrintF("Set host DPNID to %x.", m_dpnidHost);
		}
		else if (pdpPlayerInfo->dwPlayerFlags == DPNPLAYER_LOCAL)
			m_dpnidLocal = pCreatePlayer->dpnidPlayer;

		char playerName[kMaxPlayerName];
		WideToAnsi(playerName, pdpPlayerInfo->pwszName, kMaxPlayerName);

		// Display the connection message if this isn't the local player
		if (!(pdpPlayerInfo->dwPlayerFlags & DPNPLAYER_LOCAL))
		{
			ConPrintF("%s connected.", playerName);
			MessageMgr::Get()->AddLineFormat(false, "%s connected.", playerName);
		}

		SAFE_DELETE_ARRAY(pdpPlayerInfo);
	}
	else
		ConPrintF("Failed to get peer info for DPNID %x.", pCreatePlayer->dpnidPlayer);

	if (g_pNetMan->AmDefaultHost() && !IsStagingMode())
	{
		if (Client.MissionStarted())
		{
			IPtr<IQuestData> pQuest = _AppGetAggregated(IID_IQuestData);

			CNetMsg_StartMission msg;
			msg.difficulty = pQuest->Get("Difficulty");
			msg.missionID = _GetMissionData()->missNumber;

			Send(pCreatePlayer->dpnidPlayer, (void*)&msg, sizeof(CNetMsg_StartMission), NULL, DPNSEND_GUARANTEED | DPNSEND_NOLOOPBACK);
		}
	}

	if (g_Net == STATE_Client && m_bReceivedExistingPlayers || g_Net == STATE_Host)
	{
		if (pCreatePlayer->pvPlayerContext == this)
		{
			if (Debug.IsFlagSet(DEBUG_NET))
				ConPrintF("Creating local host. (%x)", pCreatePlayer->dpnidPlayer);
			m_dpnidLocal = (pCreatePlayer->dpnidPlayer);

			csReceive.Unlock();
			return;// DPN_OK;
		}

		// send Thief the new player notification in the form it expects from DPlay 4
		ZeroMemory(pDP4CreatePlayer, sizeof(DPMSG_CREATEPLAYERORGROUP));

		pDP4CreatePlayer->dwType = DPSYS_CREATEPLAYERORGROUP;
		pDP4CreatePlayer->dwPlayerType = DPPLAYERTYPE_PLAYER;
		pDP4CreatePlayer->dpId = pCreatePlayer->dpnidPlayer;

		NetMessage* pMsg = new NetMessage;
		pMsg->m_pMsgData = (BYTE*)pDP4CreatePlayer;
		pMsg->m_size = sizeof(DPMSG_CREATEPLAYERORGROUP);
		pMsg->m_dpnidSender = DPID_SYSMSG;

		m_DarkQueue.Push(pMsg);

#ifdef _THIEFBUILD
		_SFX_Play_Raw(1, 0, "pickloot.wav");
#endif

	}			

	csReceive.Unlock();
}
Esempio n. 10
0
void AuthSocket::HandleReconnectChallenge()
{
	// No header
	if(GetReadBufferSize() < 4)
		return;	

	// Check the rest of the packet is complete.
	uint8 * ReceiveBuffer = GetReadBuffer(0);
	uint16 full_size = *(uint16*)&ReceiveBuffer[2];
	sLog.outDetail("[AuthChallenge] got header, body is 0x%02X bytes", full_size);

	if(GetReadBufferSize() < (uint32)full_size+4)
		return;

	// Copy the data into our cached challenge structure
	if(full_size > sizeof(sAuthLogonChallenge_C))
	{
		Disconnect();
		return;
	}

	sLog.outDebug("[AuthChallenge] got full packet.");

	memcpy(&m_challenge, ReceiveBuffer, full_size + 4);
	RemoveReadBufferBytes(full_size + 4, false);

	// Check client build.
	if(m_challenge.build > LogonServer::getSingleton().max_build ||
		m_challenge.build < LogonServer::getSingleton().min_build)
	{
		SendChallengeError(CE_WRONG_BUILD_NUMBER);
		return;
	}

	// Check for a possible IP ban on this client.
	BAN_STATUS ipb = IPBanner::getSingleton().CalculateBanStatus(GetRemoteAddress());

	switch(ipb)
	{
	case BAN_STATUS_PERMANENT_BAN:
		SendChallengeError(CE_ACCOUNT_CLOSED);
		return;

	case BAN_STATUS_TIME_LEFT_ON_BAN:
		SendChallengeError(CE_ACCOUNT_FREEZED);
		return;
	}

	// Null-terminate the account string
	m_challenge.I[m_challenge.I_len] = 0;

	// Look up the account information
	string AccountName = (char*)&m_challenge.I;
	sLog.outDebug("[AuthChallenge] Account Name: \"%s\"", AccountName.c_str());

	m_account = AccountMgr::getSingleton().GetAccount(AccountName);
	if(m_account == 0)
	{
		sLog.outDebug("[AuthChallenge] Invalid account.");

		// Non-existant account
		SendChallengeError(CE_NO_ACCOUNT);
		return;
	}

	sLog.outDebug("[AuthChallenge] Account banned state = %u", m_account->Banned);

	// Check that the account isn't banned.
	if(m_account->Banned == 1)
	{
		SendChallengeError(CE_ACCOUNT_CLOSED);
		return;
	}
	else if(m_account->Banned > 0)
	{
		SendChallengeError(CE_ACCOUNT_FREEZED);
		return;
	}

	if(!m_account->SessionKey)
	{
		SendChallengeError(CE_SERVER_FULL);
		return;
	}

	/** burlex: this is pure speculation, I really have no idea what this does :p
	 * just guessed the md5 because it was 16 byte blocks.
	 */

	MD5_CTX ctx;
	MD5_Init(&ctx);
	MD5_Update(&ctx, m_account->SessionKey, 40);
	uint8 buffer[20];
	MD5_Final(buffer, &ctx);
	ByteBuffer buf;
	buf << uint16(2);
	buf.append(buffer, 20);
	buf << uint64(0);
	buf << uint64(0);
	Send(buf.contents(), 34);
}
Esempio n. 11
0
void AuthSocket::HandleChallenge()
{
	// No header
	if(GetReadBufferSize() < 4)
		return;	

	// Check the rest of the packet is complete.
	uint8 * ReceiveBuffer = this->GetReadBuffer(0);
#ifdef USING_BIG_ENDIAN
	uint16 full_size = swap16(*(uint16*)&ReceiveBuffer[2]);
#else
	uint16 full_size = *(uint16*)&ReceiveBuffer[2];
#endif

	sLog.outDetail("[AuthChallenge] got header, body is 0x%02X bytes", full_size);

	if(GetReadBufferSize() < uint32(full_size+4))
		return;

	// Copy the data into our cached challenge structure
	if(full_size > sizeof(sAuthLogonChallenge_C))
	{
		Disconnect();
		return;
	}

	sLog.outDebug("[AuthChallenge] got full packet.");

	memcpy(&m_challenge, ReceiveBuffer, full_size + 4);
	RemoveReadBufferBytes(full_size + 4, true);
//#ifdef USING_BIG_ENDIAN
//	uint16 build = swap16(m_challenge.build);
//	printf("Build: %u\n", build);
//#endif
 
	// Check client build.
#ifdef USING_BIG_ENDIAN
	uint16 build = swap16(m_challenge.build);
#else
	uint16 build = m_challenge.build;
#endif

	// Check client build.
	if(build > LogonServer::getSingleton().max_build)
	{
		// wtf?
		SendChallengeError(CE_WRONG_BUILD_NUMBER);
		return;
	}

	if(build < LogonServer::getSingleton().min_build)
	{
		// can we patch?
		char flippedloc[5] = {0,0,0,0,0};
		flippedloc[0] = m_challenge.country[3];
		flippedloc[1] = m_challenge.country[2];
		flippedloc[2] = m_challenge.country[1];
		flippedloc[3] = m_challenge.country[0];

		m_patch = PatchMgr::getSingleton().FindPatchForClient(build, flippedloc);
		if(m_patch == NULL)
		{
			// could not find a valid patch
			SendChallengeError(CE_WRONG_BUILD_NUMBER);
			return;
		}

		Log.Debug("Patch", "Selected patch %u%s for client.", m_patch->Version,m_patch->Locality);

		BigNumber unk;
		unk.SetRand(128);

		uint8 response[119] = {
			0x00, 0x00, 0x00, 0x72, 0x50, 0xa7, 0xc9, 0x27, 0x4a, 0xfa, 0xb8, 0x77, 0x80, 0x70, 0x22,
			0xda, 0xb8, 0x3b, 0x06, 0x50, 0x53, 0x4a, 0x16, 0xe2, 0x65, 0xba, 0xe4, 0x43, 0x6f, 0xe3,
			0x29, 0x36, 0x18, 0xe3, 0x45, 0x01, 0x07, 0x20, 0x89, 0x4b, 0x64, 0x5e, 0x89, 0xe1, 0x53,
			0x5b, 0xbd, 0xad, 0x5b, 0x8b, 0x29, 0x06, 0x50, 0x53, 0x08, 0x01, 0xb1, 0x8e, 0xbf, 0xbf,
			0x5e, 0x8f, 0xab, 0x3c, 0x82, 0x87, 0x2a, 0x3e, 0x9b, 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe1, 0x32, 0xa3,
			0x49, 0x76, 0x5c, 0x5b, 0x35, 0x9a, 0x93, 0x3c, 0x6f, 0x3c, 0x63, 0x6d, 0xc0, 0x00
		};
		Send(response, 119);
		return;
	}

	// Check for a possible IP ban on this client.
	BAN_STATUS ipb = IPBanner::getSingleton().CalculateBanStatus(GetRemoteAddress());

	switch(ipb)
	{
		case BAN_STATUS_PERMANENT_BAN:
			SendChallengeError(CE_ACCOUNT_CLOSED);
			return;

		case BAN_STATUS_TIME_LEFT_ON_BAN:
			SendChallengeError(CE_ACCOUNT_FREEZED);
			return;
	}

	// Null-terminate the account string
	m_challenge.I[m_challenge.I_len] = 0;

	// Look up the account information
	string AccountName = (char*)&m_challenge.I;
	sLog.outDebug("[AuthChallenge] Account Name: \"%s\"", AccountName.c_str());

	m_account = AccountMgr::getSingleton().GetAccount(AccountName);
	if(m_account == 0)
	{
		sLog.outDebug("[AuthChallenge] Invalid account.");

		// Non-existant account
		SendChallengeError(CE_NO_ACCOUNT);
		return;
	}

	sLog.outDebug("[AuthChallenge] Account banned state = %u", m_account->Banned);

	// Check that the account isn't banned.
	if(m_account->Banned == 1)
	{
		SendChallengeError(CE_ACCOUNT_CLOSED);
		return;
	}
	else if(m_account->Banned > 0)
	{
		SendChallengeError(CE_ACCOUNT_FREEZED);
		return;
	}

	// update cached locale
	if(!m_account->forcedLocale)
	{
		char temp[4];
		temp[0] = m_challenge.country[3];
		temp[1] = m_challenge.country[2];
		temp[2] = m_challenge.country[1];
		temp[3] = m_challenge.country[0];

		*(uint32*)&m_account->Locale[0] = *(uint32*)temp;
	}

	Sha1Hash sha;
	//uint32 tc = s.GetNumBytes();
	sha.UpdateData( s.AsByteArray(), 32 );
	sha.UpdateData( m_account->SrpHash, 20 );
	sha.Finalize();

	BigNumber x;
	x.SetBinary( sha.GetDigest(), sha.GetLength() );
	v = g.ModExp(x, N);
	b.SetRand(152);

	BigNumber gmod = g.ModExp(b, N);
	B = ((v * 3) + gmod) % N;
	ASSERT(gmod.GetNumBytes() <= 32);

	BigNumber unk;
	unk.SetRand(128);

	uint8 response[200];
	uint32 c = 0;
	response[c] = 0;										c += 1;
	response[c] = 0;										c += 1;
	response[c] = CE_SUCCESS;								c += 1;
	memcpy(&response[c], B.AsByteArray(), 32);				c += 32;
	response[c] = 1;										c += 1;
	response[c] = g.AsByteArray()[0];						c += 1;
	response[c] = 32;										c += 1;
	memcpy(&response[c], N.AsByteArray(), 32);				c += 32;
	memcpy(&response[c], s.AsByteArray(), s.GetNumBytes()); c += s.GetNumBytes();
	memcpy(&response[c], unk.AsByteArray(), 16);			c += 16;
	response[c] = 0;										c += 1;

	Send(response, c);
}
Esempio n. 12
0
void AuthSocket::HandleProof()
{
	if(GetReadBufferSize() < sizeof(sAuthLogonProof_C))
		return ;

	// patch
	if(m_patch&&!m_account)
	{
		RemoveReadBufferBytes(75,false);
		sLog.outDebug("[AuthLogonProof] Intitiating PatchJob");
		uint8 bytes[2] = {0x01,0x0a};
		Send(bytes,2);
		PatchMgr::getSingleton().InitiatePatch(m_patch, this);
		return;
	}

	if(!m_account)
		return;

	sLog.outDebug("[AuthLogonProof] Interleaving and checking proof...");

	sAuthLogonProof_C lp;
	Read(sizeof(sAuthLogonProof_C), (uint8*)&lp);

	BigNumber A;
	A.SetBinary(lp.A, 32);

	Sha1Hash sha;
	sha.UpdateBigNumbers(&A, &B, 0);
	sha.Finalize();

	BigNumber u;
	u.SetBinary(sha.GetDigest(), 20);
	
	BigNumber S = (A * (v.ModExp(u, N))).ModExp(b, N);
	uint8 t[32];
	uint8 t1[16];
	uint8 vK[40];
	memcpy(t, S.AsByteArray(), 32);
	for (int i = 0; i < 16; i++)
	{
		t1[i] = t[i*2];
	}
	sha.Initialize();
	sha.UpdateData(t1, 16);
	sha.Finalize();
	for (int i = 0; i < 20; i++)
	{
		vK[i*2] = sha.GetDigest()[i];
	}
	for (int i = 0; i < 16; i++)
	{
		t1[i] = t[i*2+1];
	}
	sha.Initialize();
	sha.UpdateData(t1, 16);
	sha.Finalize();
	for (int i = 0; i < 20; i++)
	{
		vK[i*2+1] = sha.GetDigest()[i];
	}
	m_sessionkey.SetBinary(vK, 40);

	uint8 hash[20];

	sha.Initialize();
	sha.UpdateBigNumbers(&N, NULL);
	sha.Finalize();
	memcpy(hash, sha.GetDigest(), 20);
	sha.Initialize();
	sha.UpdateBigNumbers(&g, NULL);
	sha.Finalize();
	for (int i = 0; i < 20; i++)
	{
		hash[i] ^= sha.GetDigest()[i];
	}
	BigNumber t3;
	t3.SetBinary(hash, 20);

	sha.Initialize();
	sha.UpdateData((const uint8*)m_account->UsernamePtr->c_str(), (int)m_account->UsernamePtr->size());
	sha.Finalize();

	BigNumber t4;
	t4.SetBinary(sha.GetDigest(), 20);

	sha.Initialize();
	sha.UpdateBigNumbers(&t3, &t4, &s, &A, &B, &m_sessionkey, NULL);
	sha.Finalize();

	BigNumber M;
	M.SetBinary(sha.GetDigest(), 20);

	// Compare M1 values.
	if(memcmp(lp.M1, M.AsByteArray(), 20) != 0)
	{
		// Authentication failed.
		//SendProofError(4, 0);
		SendChallengeError(CE_NO_ACCOUNT);
		sLog.outDebug("[AuthLogonProof] M1 values don't match.");
		return;
	}

	// Store sessionkey
	m_account->SetSessionKey(m_sessionkey.AsByteArray());

	// let the client know
	sha.Initialize();
	sha.UpdateBigNumbers(&A, &M, &m_sessionkey, 0);
	sha.Finalize();

	SendProofError(0, sha.GetDigest());
	sLog.outDebug("[AuthLogonProof] Authentication Success.");

	// we're authenticated now :)
	m_authenticated = true;

	// Don't update when IP banned, but update anyway if it's an account ban
	sLogonSQL->Execute("UPDATE accounts SET lastlogin=NOW(), lastip='%s' WHERE acct=%u;", GetRemoteIP().c_str(), m_account->AccountId);
}
Esempio n. 13
0
void server()
{
    int i, j, run_length = 0, print_lock = 0;
    short print_Requested = 0;
    char * all_strings;
	struct table t;
	Create_table(&t);
	Message_t msg;
	msg = (Message_t)malloc(sizeof(struct message));

	openPort(SERVER_PORT);
	while(1)
	{
            print_lock = 0;
			for(i = 0; i < 10; i++)
				if(t.status[i] == LOCKED)
				{
					msg->error_code = -1;
					print_lock = 1;
				}

			if(print_Requested && !print_lock)
			{

				for(i = 0; i < 10; i++)
				{
				 if(t.entries[i]!=NULL)
                    run_length += strlen(t.entries[i]);
				}

				all_strings = malloc((run_length+10) * sizeof(char));
				run_length = 0;
				for(i = 0; i < 10; i++)
				{
					 if(t.entries[i]!=NULL)
					 {
					     for(j = 0; j < strlen(t.entries[i]); j++)
                            all_strings[run_length++] = t.entries[i][j];
						all_strings[run_length++] = '\n';
					 }

				}
				j=0;
				msg->total_size = run_length;
				msg->error_code = 1; //Extended transmission
				while((run_length = run_length - 10) > -9)
				{
					char line[MESSAGE_LENGTH] = "";
					for(i = 0; (i < MESSAGE_LENGTH) && (j < msg->total_size); i++)
						line[i] = all_strings[j++];
					memcpy(msg->msg, line, MESSAGE_LENGTH * sizeof(char));
					if(j >= msg->total_size)
						msg->error_code = 0; //End of transmission
					Send(msg->reply_port, msg);
				}
                print_lock = 0;
                print_Requested = 0;
			}


		Receive(SERVER_PORT, msg);

		//also, take care of print request
		if(msg->operation == PRINT)
		{
			//check if anything is locked
			for(i = 0; i < 10; i++)
				if(t.status[i] == LOCKED)
				{
					msg->error_code = -1;
					print_lock = 1;
					print_Requested = 1;
				}
			if(!print_lock)
			{
				for(i = 0; i < 10; i++)
					run_length += strlen(t.entries[i]);

				all_strings = malloc((run_length + 10) * sizeof(char));
				run_length = 0;
				for(i = 0; i < 10; i++)
				{
					for(j = 0; j < strlen(t.entries[i]); j++)
						all_strings[run_length++] = t.entries[i][j];
					all_strings[run_length++] = '\n';
				}
				j=0;
				msg->total_size = run_length;
				msg->error_code = 1; //Extended transmission
				while((run_length = run_length - 10) > -9)
				{
					char line[MESSAGE_LENGTH] = "";
					for(i = 0; (i < MESSAGE_LENGTH) && (j < msg->total_size); i++)
						line[i] = all_strings[j++];
					memcpy(msg->msg, line, MESSAGE_LENGTH * sizeof(char));
					if(j >= msg->total_size)
						msg->error_code = 0; //End of transmission
					Send(msg->reply_port, msg);
				}
			print_lock = 0;
			print_Requested = 0;
			}
			else
			{
			    continue;
			}

		}
		else if( t.status[msg->row] == LOCKED ) //Resource is locked
		{
			if(msg->reply_port != t.locker[msg->row]) //Resource is locked by some other client, cannot lock
				msg->error_code = -1;
			else //Resource requestor is also the resource locker
			{
				if(msg->error_code == 1) //Extended transmission ongoing, more msgs to come
				{
					if(msg->operation == ADD)
						msg->error_code = Add_Entry(&t, msg->row, msg->msg, false);
					else if(msg->operation == MODIFY)
						msg->error_code = Modify_Entry(&t, msg->row, msg->msg, false);
				}
				else //Last message of extended transmission
				{
					if(msg->operation == ADD)
						msg->error_code = Add_Entry(&t, msg->row, msg->msg, false);
					else if(msg->operation == MODIFY)
						msg->error_code = Modify_Entry(&t, msg->row, msg->msg, false);

					Unlock(&t, msg->row);
				}
			}
		}
		else //Not locked
		{
			if(msg->error_code == 1) //Extended transmission, lock
			{
				Lock(&t, msg->row, msg->reply_port);
				if(msg->operation == ADD)
					msg->error_code = Add_Entry(&t, msg->row, msg->msg, true);
				else if(msg->operation == MODIFY)
					msg->error_code = Modify_Entry(&t, msg->row, msg->msg, true);
			}
			else
			{
				if(msg->operation == ADD)
					msg->error_code = Add_Entry(&t, msg->row, msg->msg, true);
				else if(msg->operation == MODIFY)
					msg->error_code = Modify_Entry(&t, msg->row, msg->msg, true);
				else
					msg->error_code = Delete_Entry(&t, msg->row);

			}
		}
		Send(msg->reply_port, msg);

	}

	closePort(SERVER_PORT);
}
Esempio n. 14
0
File: test.c Progetto: rahuln32/test
int main(int argc, char*argv[]) {
	fprintf(stderr, "\nThread number - 	%s\n", argv[1]);
	puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
	int sockfd = Create();
	int schedulerfd = Create();
	//int schedulerSocket = Create();
	char *temp = NULL;
	char buff[7], accept[256];
	int panningSpeed = 0;
	//char buff2[10];

	if (Connect("localhost", 35000, sockfd) < 0) {
		printf("error in connecting");
		exit(0);
	}
	if (Connect("localhost", 35001, schedulerfd) < 0) {
		printf("error in connecting to scheduler");
		exit(0);
	}
	int n = Receive(sockfd, accept, 256);
	accept[n] = 0;
	if (strcasecmp(accept, "REJECT") == 0) {
		fprintf(stderr, "SERVER REJECTED CONNECTION: PLEASE TRY AGAIN LATER");
		exit(0);
	} else {
		fprintf(stderr, "SERVER ACCEPTED CONNECTION");
	}
	char* images[5];
	images[0] = "lala1.png";
	images[1] = "lala2.png";
	images[2] = "lala3.png";
	images[3] = "lala4.png";
	images[4] = "lala5.png";

	srand(time(NULL));
	int randomNumber = ((rand() + getpid()) % 5) + 1;
	int count = 1;

	//just a test to prove that we are using multithreading!
#ifdef DEBUG
	fprintf(stderr, "\nPID = %d\n", getpid());
#endif

	while (randomNumber != 0) {
		char *randomImage = images[(rand() + getpid())
				% (sizeof(images) / sizeof(images[0]))];
		Send(sockfd, randomImage, strlen(randomImage));
		int n = 0;

		n = Receive(sockfd, buff, sizeof(int) + 1);
		buff[n] = 0;
		//the server returns the image size as 0 if it does not intend to send the image
		if(atoi(buff) != 0){

			fprintf(stderr, "\nNumber of bytes read for size= %d\n", n);
			temp = (char*) malloc(sizeof(char) * atoi(buff));
			int m = Receive(sockfd, temp, atoi(buff));
			fprintf(stderr, "bytes read=%d  size given =%d\n", m, atoi(buff));

			int i, j, temp1;
			i = 0;
			j = strlen(temp) - 1;
			while (i < j) {
				temp1 = temp[i];
				temp[i++] = temp[j];
				temp[j--] = temp1;
			}
			char countChar[5];
			sprintf(countChar, "%d", count);
			char path[100];
			strcpy(path, "./copyOfRequest");

			//uncomment if you want to have the image files stored in a seperate folder
			//strcpy(path, "./bin/copyOfRequest");

			strcat(path, countChar);
			strcat(path, "threadNo");
			strcat(path, argv[1]);
			strcat(path, randomImage);

			writeFile(temp, atoi(buff), path);
			fprintf(stderr, "write successful");
		}
		else
			fprintf(stderr, "\nServer rejected the request \n");
		randomNumber -= 1;
		count += 1;

		//get the panning speed and send it
		panningSpeed = getPanningSpeed(panningSpeed);
		char tempy[256];
		sprintf(tempy, "%d", panningSpeed);
		Send(schedulerfd, tempy, strlen(tempy));
	}
	char tempy[256];
	panningSpeed = -1;
	sprintf(tempy, "%d", panningSpeed);

	//send the panning speed as -1 to indicate to the server that the client is shutting down
	Send(schedulerfd, tempy, strlen(tempy));
	Close(sockfd);
	return EXIT_SUCCESS;
}
Esempio n. 15
0
void CUser::WarehouseProcess(Packet & pkt)
{
	Packet result(WIZ_WAREHOUSE);
	CNpc * pNpc;
	uint32 itemid, count;
	uint16 npcid, reference_pos;
	uint8 page, srcpos, destpos;
	_ITEM_TABLE* pTable = nullptr;
	uint8 command = pkt.read<uint8>();
	bool bResult = false;

	if (isDead())
		return;

	if (isTrading())
		goto fail_return;

	if (command == WAREHOUSE_OPEN)
	{
		result << uint8(WAREHOUSE_OPEN) << uint8(WAREHOUSE_OPEN) << GetInnCoins();
		for (int i = 0; i < WAREHOUSE_MAX; i++)
		{
			_ITEM_DATA *pItem = &m_sWarehouseArray[i];
			result	<< pItem->nNum << pItem->sDuration << pItem->sCount
					<< uint8(0) << uint16(0) << uint16(0) << uint16(0) << uint16(0);
		}
		Send(&result);
		return;
	}

	pkt >> npcid >> itemid >> page >> srcpos >> destpos;

	pNpc = g_pMain->m_arNpcArray.GetData(npcid);
	if (pNpc == nullptr
		|| pNpc->GetType() != NPC_WAREHOUSE
		|| !isInRange(pNpc, MAX_NPC_RANGE))
		goto fail_return;

	pTable = g_pMain->GetItemPtr( itemid );
	if( !pTable ) goto fail_return;
	reference_pos = 24 * page;

	// TO-DO: Clean up this entire method. It's horrendous!
	switch (command)
	{
	/* stuff going into the inn */
	case WAREHOUSE_INPUT:
		pkt >> count;

		// Handle coin input.
		if (itemid == ITEM_GOLD)
		{
			if (!hasCoins(count)
				|| GetInnCoins() + count > COIN_MAX)
				goto fail_return;

			m_iBank += count;
			m_iGold -= count;
			break;
		}

		if (srcpos > HAVE_MAX
			|| reference_pos + destpos > WAREHOUSE_MAX
			|| itemid >= ITEM_NO_TRADE) // Cannot be traded, sold or stored (note: don't check the race, as these items CAN be stored).
			goto fail_return;

		if (m_sItemArray[SLOT_MAX+srcpos].isSealed()
			|| m_sItemArray[SLOT_MAX+srcpos].isRented())
			goto fail_return;

		if( m_sItemArray[SLOT_MAX+srcpos].nNum != itemid ) goto fail_return;
		if( m_sWarehouseArray[reference_pos+destpos].nNum && !pTable->m_bCountable ) goto fail_return;
		if( m_sItemArray[SLOT_MAX+srcpos].sCount < count ) goto fail_return;
		m_sWarehouseArray[reference_pos+destpos].nNum = itemid;
		m_sWarehouseArray[reference_pos+destpos].sDuration = m_sItemArray[SLOT_MAX+srcpos].sDuration;
		m_sWarehouseArray[reference_pos+destpos].nSerialNum = m_sItemArray[SLOT_MAX+srcpos].nSerialNum;
		if( pTable->m_bCountable == 0 && m_sWarehouseArray[reference_pos+destpos].nSerialNum == 0 )
			m_sWarehouseArray[reference_pos+destpos].nSerialNum = g_pMain->GenerateItemSerial();

		if( pTable->m_bCountable ) {
			m_sWarehouseArray[reference_pos+destpos].sCount += (unsigned short)count;
		}
		else {
			m_sWarehouseArray[reference_pos+destpos].sCount = m_sItemArray[SLOT_MAX+srcpos].sCount;
		}

		if( !pTable->m_bCountable ) {
			m_sItemArray[SLOT_MAX+srcpos].nNum = 0;
			m_sItemArray[SLOT_MAX+srcpos].sDuration = 0;
			m_sItemArray[SLOT_MAX+srcpos].sCount = 0;
			m_sItemArray[SLOT_MAX+srcpos].nSerialNum = 0;
		}
		else {
			m_sItemArray[SLOT_MAX+srcpos].sCount -= (unsigned short)count;
			if( m_sItemArray[SLOT_MAX+srcpos].sCount <= 0 ) {
				m_sItemArray[SLOT_MAX+srcpos].nNum = 0;
				m_sItemArray[SLOT_MAX+srcpos].sDuration = 0;
				m_sItemArray[SLOT_MAX+srcpos].sCount = 0;
				m_sItemArray[SLOT_MAX+srcpos].nSerialNum = 0;
			}
		}

		SendItemWeight();
		break;

	/* stuff being taken out of the inn */
	case WAREHOUSE_OUTPUT:
		pkt >> count;

		if (itemid == ITEM_GOLD)
		{
			if (!hasInnCoins(count)
				|| GetCoins() + count > COIN_MAX)
				goto fail_return;

			m_iGold += count;
			m_iBank -= count;
			break;
		}

		if (reference_pos + srcpos > WAREHOUSE_MAX
			|| destpos > HAVE_MAX)
			goto fail_return;

		if (pTable->m_bCountable) {	// Check weight of countable item.
			if (((pTable->m_sWeight * count)   + m_sItemWeight) > m_sMaxWeight) {			
				goto fail_return;
			}
		}
		else {	// Check weight of non-countable item.
			if ((pTable->m_sWeight + m_sItemWeight) > m_sMaxWeight) {
				goto fail_return;
			}
		}		

		if( m_sWarehouseArray[reference_pos+srcpos].nNum != itemid ) goto fail_return;
		if( m_sItemArray[SLOT_MAX+destpos].nNum && !pTable->m_bCountable ) goto fail_return;
		if( m_sWarehouseArray[reference_pos+srcpos].sCount < count ) goto fail_return;
		m_sItemArray[SLOT_MAX+destpos].nNum = itemid;
		m_sItemArray[SLOT_MAX+destpos].sDuration = m_sWarehouseArray[reference_pos+srcpos].sDuration;
		m_sItemArray[SLOT_MAX+destpos].nSerialNum = m_sWarehouseArray[reference_pos+srcpos].nSerialNum;
		if( pTable->m_bCountable )
			m_sItemArray[SLOT_MAX+destpos].sCount += (unsigned short)count;
		else {
			if( m_sItemArray[SLOT_MAX+destpos].nSerialNum == 0 )
				m_sItemArray[SLOT_MAX+destpos].nSerialNum = g_pMain->GenerateItemSerial();
			m_sItemArray[SLOT_MAX+destpos].sCount = m_sWarehouseArray[reference_pos+srcpos].sCount;
		}
		if( !pTable->m_bCountable ) {
			m_sWarehouseArray[reference_pos+srcpos].nNum = 0;
			m_sWarehouseArray[reference_pos+srcpos].sDuration = 0;
			m_sWarehouseArray[reference_pos+srcpos].sCount = 0;
			m_sWarehouseArray[reference_pos+srcpos].nSerialNum = 0;
		}
		else {
			m_sWarehouseArray[reference_pos+srcpos].sCount -= (unsigned short)count;
			if( m_sWarehouseArray[reference_pos+srcpos].sCount <= 0 ) {
				m_sWarehouseArray[reference_pos+srcpos].nNum = 0;
				m_sWarehouseArray[reference_pos+srcpos].sDuration = 0;
				m_sWarehouseArray[reference_pos+srcpos].sCount = 0;
				m_sWarehouseArray[reference_pos+srcpos].nSerialNum = 0;
			}
		}

		SendItemWeight();		
		//TRACE("WARE OUTPUT : %s %s %d %d %d %d %d", m_id, m_Accountid, ITEM_WAREHOUSE_GET, 0, itemid, count, m_sItemArray[SLOT_MAX+destpos].sDuration );
		break;
	case WAREHOUSE_MOVE:
		if( reference_pos+srcpos > WAREHOUSE_MAX ) goto fail_return;
		if( m_sWarehouseArray[reference_pos+srcpos].nNum != itemid ) goto fail_return;
		if( m_sWarehouseArray[reference_pos+destpos].nNum ) goto fail_return;
		m_sWarehouseArray[reference_pos+destpos].nNum = itemid;
		m_sWarehouseArray[reference_pos+destpos].sDuration = m_sWarehouseArray[reference_pos+srcpos].sDuration;
		m_sWarehouseArray[reference_pos+destpos].sCount = m_sWarehouseArray[reference_pos+srcpos].sCount;
		m_sWarehouseArray[reference_pos+destpos].nSerialNum = m_sWarehouseArray[reference_pos+srcpos].nSerialNum;

		m_sWarehouseArray[reference_pos+srcpos].nNum = 0;
		m_sWarehouseArray[reference_pos+srcpos].sDuration = 0;
		m_sWarehouseArray[reference_pos+srcpos].sCount = 0;
		m_sWarehouseArray[reference_pos+srcpos].nSerialNum = 0;
		break;
	case WAREHOUSE_INVENMOVE:
		if( itemid != m_sItemArray[SLOT_MAX+srcpos].nNum )
			goto fail_return;
		{
			short duration = m_sItemArray[SLOT_MAX+srcpos].sDuration;
			short itemcount = m_sItemArray[SLOT_MAX+srcpos].sCount;
			uint64 serial = m_sItemArray[SLOT_MAX+srcpos].nSerialNum;
			m_sItemArray[SLOT_MAX+srcpos].nNum = m_sItemArray[SLOT_MAX+destpos].nNum;
			m_sItemArray[SLOT_MAX+srcpos].sDuration = m_sItemArray[SLOT_MAX+destpos].sDuration;
			m_sItemArray[SLOT_MAX+srcpos].sCount = m_sItemArray[SLOT_MAX+destpos].sCount;
			m_sItemArray[SLOT_MAX+srcpos].nSerialNum = m_sItemArray[SLOT_MAX+destpos].nSerialNum;

			m_sItemArray[SLOT_MAX+destpos].nNum = itemid;
			m_sItemArray[SLOT_MAX+destpos].sDuration = duration;
			m_sItemArray[SLOT_MAX+destpos].sCount = itemcount;
			m_sItemArray[SLOT_MAX+destpos].nSerialNum = serial;
		}
		break;
	}

	bResult = true;

fail_return: // hmm...
	result << uint8(command) << bResult;
	Send(&result);
}
Esempio n. 16
0
//==============================================================================
// SendToAll()
//
// Sends a packet to all players.
//==============================================================================
void CDarkPeer::SendToAll(void* pData, DWORD dwDataSize, DWORD dwTimeout, DWORD dwFlags)
{
	Send(ALL_PLAYERS, pData, dwDataSize, dwTimeout, dwFlags);
}
Esempio n. 17
0
status_t MSNConnection::HandleCHL( Command * command ) {
	LOG(kProtocolName, liDebug, "C %lX: Processing CHL", this);

	const char *challenge = command->Param(0);
	int i = 0;
	unsigned char buf[256];
	char chlString[128];
	long long high = 0;
	long long low = 0;
	long long temp = 0;
	long long key = 0;
	long long bskey = 0;
	int *chlStringArray = (int *)chlString;
	int *md5hash = (int *)buf;
	char hash1a[17];
	char hash2a[17];

	sprintf((char *)buf + 16, "%s%s", challenge, kClientCode);
	MD5(buf + 16, strlen((char *)buf + 16), buf);
	for (i = 0; i < 16; i++) {
		sprintf((char *)buf + 16 + i * 2,"%02x", buf[i]);
	};
	
	for (i = 0; i < 4; i++) {
	   md5hash[i] = md5hash[i] & 0x7FFFFFFF;
	};
	
	i = (strlen(challenge) + strlen(kClientID) + 7) & 0xF8;
	sprintf(chlString,"%s%s00000000", challenge, kClientID);
	chlString[i] = 0;
	
	for (i = 0; i < (int)strlen(chlString) / 4; i += 2) {
		temp = chlStringArray[i];
		
		temp = (0x0E79A9C1 * temp) % 0x7FFFFFFF;
		temp += high;
		temp = md5hash[0] * temp + md5hash[1];
		temp = temp % 0x7FFFFFFF;
		
		high = chlStringArray[i + 1];
		high = (high + temp) % 0x7FFFFFFF;
		high = md5hash[2] * high + md5hash[3];
		high = high % 0x7FFFFFFF;
		
		low = low + high + temp;
	};
	
	high = (high + md5hash[1]) % 0x7FFFFFFF;
	low = (low + md5hash[3]) % 0x7FFFFFFF;
	
	key = (low << 32) + high;
	for (i= 0; i < 8; i++) {
		bskey <<= 8;
		bskey += key & 255;
		key >>=8;
	};
	
	strncpy((char *)hash1a, (char *)buf + 16, 16);
	strncpy((char *)hash2a, (char *)buf + 32, 16);
	hash1a[16] = '\0';
	hash2a[16] = '\0';
	
	sprintf((char *)buf, "%llx%llx", strtoull(hash1a,NULL,16) ^ bskey,
		strtoull(hash2a,NULL,16) ^ bskey);

	Command *reply = new Command("QRY");
	reply->AddParam(kClientID);
	reply->AddPayload((char *)buf, 32);
	
	Send(reply);
	reply->Debug();
	
	return B_OK;
};
Esempio n. 18
0
long udp::Send(char* const buffer) {
	return Send(buffer, strlen(buffer));
}
void CUser::ZoneChange(int zone, float x, float z)
{
	m_bZoneChangeFlag = true;

	C3DMap* pMap = NULL;
	_ZONE_SERVERINFO *pInfo = NULL;

	pMap = g_pMain->GetZoneByID(zone);
	if (!pMap) 
		return;

	if( pMap->m_bType == 2 ) {	// If Target zone is frontier zone.
		if( GetLevel() < 20 && g_pMain->m_byBattleOpen != SNOW_BATTLE)
			return;
	}

	if( g_pMain->m_byBattleOpen == NATION_BATTLE )	{		// Battle zone open
		if( m_bZone == BATTLE_ZONE )	{
			if( pMap->m_bType == 1 && m_bNation != zone && (zone < 10 || zone > 21))	{	// ???? ?????? ???? ????..
				if( m_bNation == KARUS && !g_pMain->m_byElmoradOpenFlag )	{
					TRACE("#### ZoneChange Fail ,,, id=%s, nation=%d, flag=%d\n", GetName(), m_bNation, g_pMain->m_byElmoradOpenFlag);
					return;
				}
				else if( m_bNation == ELMORAD && !g_pMain->m_byKarusOpenFlag )	{
					TRACE("#### ZoneChange Fail ,,, id=%s, nation=%d, flag=%d\n", GetName(), m_bNation, g_pMain->m_byKarusOpenFlag);
					return;
				}
			}
		}
		else if( pMap->m_bType == 1 && m_bNation != zone && (zone < 10 || zone > 21)) {		// ???? ?????? ???? ????..
			return;
		}
//
		else if( pMap->m_bType == 2 && zone == ZONE_RONARK_LAND ) {	 // You can't go to frontier zone when Battlezone is open.
			Packet result(WIZ_WARP_LIST, uint8(2));
			result << uint8(0);
			Send(&result);
			return;
		}
//
	}
	else if( g_pMain->m_byBattleOpen == SNOW_BATTLE )	{					// Snow Battle zone open
		if( pMap->m_bType == 1 && m_bNation != zone ) {		// ???? ?????? ???? ????..
			return;
		}
		else if( pMap->m_bType == 2 && (zone == ZONE_RONARK_LAND || zone == ZONE_BATTLE ) ) {			// You can't go to frontier zone when Battlezone is open.
			return;
		}
	}
	else	{					// Battle zone close
		if( pMap->m_bType == 1 && m_bNation != zone && (zone < 10 || zone > 21))
			return;
	}

	m_bWarp = 0x01;

	UserInOut(INOUT_OUT);

	if( m_bZone == ZONE_SNOW_BATTLE )	{
		//TRACE("ZoneChange - name=%s\n", m_id);
		SetMaxHp( 1 );
	}

	bool bSameZone = (GetZoneID() == zone);
	m_bZone = zone;
	m_curx = x;
	m_curz = z;

	if (!bSameZone)
	{
		SetZoneAbilityChange();

		/* 
			Here we also send a clan packet with subopcode 0x16 (with a byte flag of 2) if war zone/Moradon
			or subopcode 0x17 (with nWarEnemyID) for all else
		*/
#if 0
		if (isInClan())
		{
			CKnights * pKnights = g_pMain->GetClanPtr(GetClanID());
			if (pKnights != NULL
					&& pKnights->bKnightsWarStarted)
			{
				Packet clanPacket(WIZ_KNIGHTS_PROCESS);
				if ((GetZoneID() / 100) == 1
					|| GetZoneID() == 21)
					clanPacket << uint8(0x17) << uint8(2);
				else 
					clanPacket << uint16(0x16) << uint16(0 /*nWarEnemyID*/);

				Send(&clanPacket);
			}
		}
#endif


		if (GetZoneID() == ZONE_SNOW_BATTLE)
		{
			//TRACE("ZoneChange - name=%s\n", GetName());
			SetMaxHp();
		}

		if (isInParty())
			PartyRemove(GetSocketID());

		ResetWindows();
	}


	m_pMap = pMap;

	//TRACE("ZoneChange ,,, id=%s, nation=%d, zone=%d, x=%.2f, z=%.2f\n", GetName(), m_bNation, zone, x, z);
	
	if( g_pMain->m_nServerNo != pMap->m_nServerNo ) {
		pInfo = g_pMain->m_ServerArray.GetData( pMap->m_nServerNo );
		if( !pInfo ) 
			return;

		UserDataSaveToAgent();

		m_bLogout = 2;	// server change flag
		SendServerChange(pInfo->strServerIP, 2);
		return;
	}
	
	SetRegion(GetNewRegionX(), GetNewRegionZ());

	Packet result(WIZ_ZONE_CHANGE, uint8(3)); // magic numbers, sigh.
	result << uint16(GetZoneID()) << GetSPosX() << GetSPosZ() << GetSPosY() << g_pMain->m_byOldVictory;
	Send(&result);

	if (!m_bZoneChangeSameZone)
	{
		m_sWhoKilledMe = -1;
		m_iLostExp = 0;
		m_bRegeneType = 0;
		m_tLastRegeneTime = 0;
		m_sBind = -1;
		InitType3();
		InitType4();
		SetUserAbility();
	}	

	result.Initialize(AG_ZONE_CHANGE);
	result << GetSocketID() << GetZoneID();
	Send_AIServer(&result);

	m_bZoneChangeSameZone = false;
	m_bZoneChangeFlag = false;
}
void CUser::ZoneChange(int zone, float x, float z)
{
	m_bZoneChangeFlag = TRUE;

	int send_index = 0, zoneindex = 0;
	char send_buff[128];
	C3DMap* pMap = NULL;
	_ZONE_SERVERINFO *pInfo = NULL;

	if( g_serverdown_flag ) return;

	pMap = m_pMain->GetZoneByID(zone);
	if (!pMap) 
		return;

	m_pMap = pMap;
	if( pMap->m_bType == 2 ) {	// If Target zone is frontier zone.
		if( m_pUserData->m_bLevel < 20 && m_pMain->m_byBattleOpen != SNOW_BATTLE)
			return;
	}

	if( m_pMain->m_byBattleOpen == NATION_BATTLE )	{		// Battle zone open
		if( m_pUserData->m_bZone == BATTLE_ZONE )	{
			if( pMap->m_bType == 1 && m_pUserData->m_bNation != zone )	{	// ???? ?????? ???? ????..
				if( m_pUserData->m_bNation == KARUS && !m_pMain->m_byElmoradOpenFlag )	{
					TRACE("#### ZoneChange Fail ,,, id=%s, nation=%d, flag=%d\n", m_pUserData->m_id, m_pUserData->m_bNation, m_pMain->m_byElmoradOpenFlag);
					return;
				}
				else if( m_pUserData->m_bNation == ELMORAD && !m_pMain->m_byKarusOpenFlag )	{
					TRACE("#### ZoneChange Fail ,,, id=%s, nation=%d, flag=%d\n", m_pUserData->m_id, m_pUserData->m_bNation, m_pMain->m_byKarusOpenFlag);
					return;
				}
			}
		}
		else if( pMap->m_bType == 1 && m_pUserData->m_bNation != zone ) {		// ???? ?????? ???? ????..
			return;
		}
//
		else if( pMap->m_bType == 2 && zone == ZONE_FRONTIER ) {	 // You can't go to frontier zone when Battlezone is open.
			int temp_index = 0;
			char temp_buff[3];

			SetByte( temp_buff, WIZ_WARP_LIST, temp_index );
			SetByte( temp_buff, 2, temp_index );
			SetByte( temp_buff,0, temp_index );
			Send(temp_buff, temp_index);
//
			return;
		}
//
	}
	else if( m_pMain->m_byBattleOpen == SNOW_BATTLE )	{					// Snow Battle zone open
		if( pMap->m_bType == 1 && m_pUserData->m_bNation != zone ) {		// ???? ?????? ???? ????..
			return;
		}
		else if( pMap->m_bType == 2 && (zone == ZONE_FRONTIER || zone == ZONE_BATTLE ) ) {			// You can't go to frontier zone when Battlezone is open.
			return;
		}
	}
	else	{					// Battle zone close
		if( pMap->m_bType == 1 && m_pUserData->m_bNation != zone && (zone < 10 || zone > 20))		// ???? ?????? ???? ????..
			return;
	}

	m_bWarp = 0x01;

	UserInOut( USER_OUT );

	if( m_pUserData->m_bZone == ZONE_SNOW_BATTLE )	{
		//TRACE("ZoneChange - name=%s\n", m_pUserData->m_id);
		SetMaxHp( 1 );
	}

	m_pUserData->m_bZone = zone;
	m_pUserData->m_curx = m_fWill_x = x;
	m_pUserData->m_curz = m_fWill_z = z;

	if( m_pUserData->m_bZone == ZONE_SNOW_BATTLE )	{
		//TRACE("ZoneChange - name=%s\n", m_pUserData->m_id);
		SetMaxHp();
	}

	PartyRemove(m_Sid);	// ??????? Z?????? ó??

	//TRACE("ZoneChange ,,, id=%s, nation=%d, zone=%d, x=%.2f, z=%.2f\n", m_pUserData->m_id, m_pUserData->m_bNation, zone, x, z);
	
	if( m_pMain->m_nServerNo != pMap->m_nServerNo ) {
		pInfo = m_pMain->m_ServerArray.GetData( pMap->m_nServerNo );
		if( !pInfo ) 
			return;

		UserDataSaveToAgent();
		
		CTime t = CTime::GetCurrentTime();
		m_pMain->WriteLog("[ZoneChange : %d-%d-%d] - sid=%d, acname=%s, name=%s, zone=%d, x=%d, z=%d \r\n", t.GetHour(), t.GetMinute(), t.GetSecond(), m_Sid, m_strAccountID, m_pUserData->m_id, zone, (int)x, (int)z);

		m_pUserData->m_bLogout = 2;	// server change flag
		SendServerChange(pInfo->strServerIP, 2);
		return;
	}
	
	m_pUserData->m_sBind = -1;		// Bind Point Clear...
	
	m_RegionX = (int)(m_pUserData->m_curx / VIEW_DISTANCE);
	m_RegionZ = (int)(m_pUserData->m_curz / VIEW_DISTANCE);

	SetByte( send_buff, WIZ_ZONE_CHANGE, send_index );
	SetByte( send_buff, m_pUserData->m_bZone, send_index );
	SetShort( send_buff, (WORD)m_pUserData->m_curx*10, send_index );
	SetShort( send_buff, (WORD)m_pUserData->m_curz*10, send_index );
	SetShort( send_buff, (short)m_pUserData->m_cury*10, send_index );
	SetByte( send_buff, m_pMain->m_byOldVictory, send_index );
	Send( send_buff, send_index );

	if (!m_bZoneChangeSameZone) {
		m_sWhoKilledMe = -1;
		m_iLostExp = 0;
		m_bRegeneType = 0;
		m_fLastRegeneTime = 0.0f;
		m_pUserData->m_sBind = -1;
		InitType3();
		InitType4();
	}	

	if (m_bZoneChangeSameZone) {
		m_bZoneChangeSameZone = FALSE;
	}

	send_index = 0;
	SetByte( send_buff, AG_ZONE_CHANGE, send_index );
	SetShort( send_buff, m_Sid, send_index );
	SetByte( send_buff, getZoneID(), send_index );

	m_pMain->Send_AIServer(send_buff, send_index);

	m_bZoneChangeFlag = FALSE;
}
Esempio n. 21
0
int Master::_parse_write_file(int clientfd, std::string& ip)
{
	fprintf(stderr, "request for writing ip=%s\n",ip.c_str());
	ssize_t file_no;
	size_t size, block_size;
	off_t start_point;
	Recv(clientfd, file_no);
	Recv(clientfd, start_point);
	Recv(clientfd, size);
	int fd=open(_buffered_files.at(file_no).path.c_str(), O_CREAT, S_IRUSR|S_IWUSR);
	if(-1 == fd)
	{
		fprintf(stderr, "file create error\n");
		return FAILURE;
	}
	close(fd);
	try
	{
		file_info &file=_buffered_files.at(file_no);
		block_size=_get_block_size(size);
		file.block_size=block_size;
		if(0 == file.size)
		{
			file.size=size;
		}
		node_t nodes=_select_IOnode(size, block_size);
		for(node_t::const_iterator it=nodes.begin(); 
				nodes.end()!=it; ++it)
		{
			//send read request to each IOnode
			//buffer requset
			//file_no
			//file_path
			//start_point
			//block_size
			int socket=_registed_IOnodes.at(it->second).socket;
			size_t my_block_size=it->first+block_size > file.size?file.size-it->first:block_size;
			Send(socket, WRITE_FILE);
			Send(socket, file_no);
			Sendv(socket, file.path.c_str(), file.path.size());
			Send(socket, it->first); 
			Send(socket, my_block_size); 
		}
		file.p_node=nodes;
		for(node_t::const_iterator it=file.p_node.begin();
				it !=file.p_node.end();++it)
		{
			file.nodes.insert(it->second);
		}
		Send(clientfd, SUCCESS);	
		Send(clientfd, static_cast<int>(file.p_node.size()));
		Send(clientfd, file.size);
		Send(clientfd, file.block_size);
		for(node_t::const_iterator it=file.p_node.begin(); it!=file.p_node.end(); ++it)
		{
			Send(clientfd, it->first);
			const std::string& ip=_registed_IOnodes.at(it->second).ip; 
			Sendv(clientfd, ip.c_str(), ip.size());
		}
		close(clientfd);
		return SUCCESS;
	}
	catch(std::out_of_range &e)
	{
		Send(clientfd, FAILURE);	
		close(clientfd);
		return FAILURE;
	}
}
Esempio n. 22
0
    void FetchTaskHandler(const FetchTaskMessage &message, const Theron::Address from)
        {
            std::cout<<"get data.................."<<std::endl;

            std::string url=message.fi->url;
            char curl_errbuf[CURL_ERROR_SIZE];
            CURL *curl = curl_easy_init();
            int err;

            fetch::FetchResult *result=new fetch::FetchResult();
            fetch::FetchInfo fi=*(message.fi);
            delete message.fi;
            result->type=fetch::UNKNOWN; 
            result->url=fi.url;
            result->pathList=fi.pathList;
            result->attMap=fi.attMap;
            int errCode=0;
            if(curl!=NULL) {
                curl_easy_setopt(curl, CURLOPT_URL,url.c_str());
                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errbuf);
//                curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
//                curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
                curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
                curl_easy_setopt(curl, CURLOPT_NOSIGNAL,1);
                curl_easy_setopt(curl, CURLOPT_TIMEOUT ,60);

                curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fetch_write);
                
                std::stringstream iss;
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, &iss);

                err=curl_easy_perform(curl);
                if ( !err ) 
                {
                    std::map<std::string,std::string>::iterator efit=fi.attMap.find("encode");
                    char *resStr=new char[iss.str().length()*3];
                    memset(resStr,0,iss.str().length()*3);
                    if(efit!=fi.attMap.end())
                    {
                        UErrorCode  error = U_ZERO_ERROR;
                        ucnv_convert("UTF-8",efit->second.c_str(),resStr,  iss.str().length()*3, iss.str().c_str(), iss.str().length(), &error );
                    }else
                    {
                        strcpy(resStr,iss.str().c_str());
                    }
                    TidyDoc tdoc;
//                TidyBuffer tidy_errbuf = {0};
//            TidyBuffer docbuf = {0};
                
                    tdoc = tidyCreate();
                    tidyOptSetInt(tdoc, TidyWrapLen, 4096);
//                tidySetErrorBuffer( tdoc, &tidy_errbuf );
                    tidyOptSetBool( tdoc, TidyXmlOut, yes );
                    tidyOptSetBool(tdoc, TidyQuoteNbsp, no);
                    tidyOptSetBool(tdoc, TidyForceOutput, yes); /* try harder */ 
//                tidyOptSetBool( tdoc, TidyXmlDecl, yes );  
                    tidyOptSetBool(tdoc, TidyQuiet, yes);
                    tidyOptSetBool(tdoc, TidyShowWarnings, no);
                    tidyOptSetValue(tdoc,TidyDoctype,"omit");

                    tidyOptSetBool(tdoc, TidyFixBackslash, yes);
                    
                    tidyOptSetBool(tdoc, TidyMark, no);

                    tidySetCharEncoding(tdoc,"utf8");
//                tidyBufInit(&docbuf);
//                    err = tidyParseBuffer(tdoc, &docbuf); 
                    err = tidyParseString(tdoc, resStr); 
                    if ( err >= 0 ) {
                        err = tidyCleanAndRepair(tdoc); /* fix any problems */ 
                        if ( err >= 0 ) {
//                            err=tidyRunDiagnostics(tdoc); /* load tidy error buffer */ 
//                            if ( err >= 0 ) {
//                                std::cout<<"tidy error:"<<tidy_errbuf.bp<<std::endl; /* show errors */ 
                            TidyBuffer outbuf = {0};
                            tidyBufInit(&outbuf);
                            tidySaveBuffer( tdoc, &outbuf );
                            std::stringstream hss;
                            hss<<(char*)outbuf.bp;
                            tidyBufFree(&outbuf);
                            result->result=hss.str();
//                        }
//                        else
//                        {
//                                errCode=-5;
//                            }

                            
                        }else
                        {
                            errCode=-4;
                        }
                    }else
                    {
                        errCode=-3;
                    }
                    //                tidyBufFree(&tidy_errbuf);
//            tidyBufFree(&docbuf);
                    tidyRelease(tdoc);

                    delete [] resStr;
                }else
                {
                    errCode=-2;
                }
            }else
            {
                errCode=-1;
            }
            if(errCode<0)
            {
                std::stringstream ess;
                ess<<errCode;
                result->type=fetch::ERROR;
                result->result=ess.str();
            }
            curl_easy_cleanup(curl);
            Send(FetchResultMessage(result), from);
        }
	void p2p_connection::handle_read_body(const boost::system::error_code& error)
	{
		if (!error)
		{
			size_t bodyLength = packet_.body_length();
			// if this is a single byte ping packet, ping back, or just ignore if it's a reply.
			if (bodyLength == 1)
			{
				unsigned char ping = packet_.body()[0];
				if (ping == 0)
				{
					unsigned char ping[1];
					ping[0] = 1;
					Send(ping, 1);
				}
			}
			else
			{
			  if (_remoteId == "")
			  {
				  std::string body(packet_.body(), packet_.body() + bodyLength);
				  _remoteId = body.substr(0, bodyLength);
				  if (_localId != _remoteId)
				  {
					  NodeConnected(isIncoming_, shared_from_this(), _remoteId);

					  std::stringstream id_stream;
					  id_stream << _localId;

					  if (isIncoming_)
						  Send(std::string(id_stream.str()));
				  }
				  else
				  {
					  std::stringstream ss;
					  ss << "Dropped connection to self. " << socket_.remote_endpoint();
					  Log(std::string(ss.str()));

					  //socket_.shutdown(boost::asio::socket_base::shutdown_both);
					  //_io_service.stop();
					  return;
				  }
			  }
			  else
				  ReceivedData(shared_from_this(), packet_);
			}
			
			if (write_queue_.empty())
			{
				// todo: this would be better if it continually checked for 3 secs if theres any queued outgoing,
				// if any appear, it continues, if not, it pings 
				// (or else we have to wait until the next round to send) up to 3 secs of potential lag with thread::sleep method
				boost::this_thread::sleep(boost::posix_time::milliseconds(3000));

				unsigned char ping[1];
				ping[0] = 0;
				Send(ping, 1);
			}

			boost::asio::async_write(socket_,
   									 boost::asio::buffer(write_queue_.front().data(),
									 write_queue_.front().length()),
									 boost::bind(&p2p_connection::handle_write, shared_from_this(),
									 boost::asio::placeholders::error));
		}
		else
		{
			// we got disconnected or sumfin
			if (error)
				NodeDisconnected(_remoteId, std::string("(handle_read_body) ").append(error.message()));
			else
				NodeDisconnected(_remoteId, "(handle_read_body) no error");
		}
	}
Esempio n. 24
0
int CLircdClient::SendOnce(string device, string key)
{
	return Send("SEND_ONCE",device,key);
}
Esempio n. 25
0
void Client::sendGotBlocks(v3s16 block)
{
	NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
	pkt << (u8) 1 << block;
	Send(&pkt);
}
Esempio n. 26
0
File: ozipc.c Progetto: Fluray/OrzOs
s64int OzSend(s64int pid, void *buffer, u64int size)
{
    return Send(lookupPid(pid), buffer, size);
}
Esempio n. 27
0
	/// <summary>
	/// Sends the specified buf.
	/// </summary>
	/// <param name="buf">待发送的常量字符串指针.</param>
	/// <param name="callback">本次发送是否需要设置发送完成的回调.</param>
	void TcpConnection::Send( const char* buf, bool callback /*= false*/ )
	{
		string msg(buf);
		Send( msg ,callback);
	}
Esempio n. 28
0
void CWin32Socket::ServiceL(TWin32Message& aMessage)
	{
	switch (aMessage.OppCode())
		{
		case EConnect:
			{
			Connect(aMessage);
			break;
			}
		case ECancelConnect:
			{
			if (iConnectMessage)
				{
				Complete(iConnectMessage, KErrCancel);
				}
			break;
			}
		case ESend:
			{
			Send(aMessage);
			break;
			}
		case ECancelSend:
			{
			if (iSendMessage)
				{
				Complete(iSendMessage, KErrCancel);
				}
			break;
			}
		case ESendTo:
			{
			SendTo(aMessage);
			break;
			}
		case ECancelSendTo:
			{
			if (iSendMessage)
				{
				Complete(iSendMessage, KErrCancel);
				}
			break;
			}
		case EReceive:
			{
			Receive(aMessage);
			break;
			}
		case ECancelReceive:
			{
			if (iReceiveMessage)
				{
				Complete(iReceiveMessage, KErrCancel);
				}
			break;
			}
		case EReceiveFrom:
			{
			ReceiveFrom(aMessage);
			break;
			}
		case ECancelReceiveFrom:
			{
			if (iReceiveMessage)
				{
				Complete(iReceiveMessage, KErrCancel);
				}
			break;
			}
		case EGetSocketName:
			{
			GetSocketName(aMessage);
			break;
			}
		case EBind:
			{
			Bind(aMessage);
			break;
			}
		case EGetPeerName:
			{
			GetPeerName(aMessage);
			break;
			}
		case EListen:
			{
			Listen(aMessage);
			break;
			}
		case EAccept:
			{
			Accept(aMessage);
			break;
			}
		case ECancelAccept:
			{
			if (iAcceptMessage)
				{
				Complete(iAcceptMessage, KErrCancel);
				}
			break;
			}
		case EGetOption:
			{
			GetOption(aMessage);
			break;
			}
		case ESetOption:
			{
			SetOption(aMessage);
			break;
			}
		default:
			{
			__ASSERT_DEBUG(EFalse, Panic(EWinSockPrtInvalidSocketOppCode));
			}
		}
	}
Esempio n. 29
0
/*
 * put_file() - send a file to the server accessible via the given socket fd
 */
void put_file(int fd, char *put_name) 
{
    /* open file and check for error */
    FILE * fp = fopen(put_name, "rb");   
    if (fp == NULL)
        die("Put_file file error", "file not found");
     
    /* get file size */
    fseek(fp, 0, SEEK_END);
    int file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char file_buf[file_size];

    /* store file in buffer */
    size_t bytes_read = fread(file_buf, sizeof(unsigned char), file_size, fp);
    if (bytes_read != file_size)
    {
            fclose(fp);
            die("Put_file fread error", "bytes_read != file_size");
    }

    /* hacky way to get number of digits in the file size */
    int j = 1, temp_size = file_size / 10; //acount for file_size of 0
    while (temp_size)
    {
        j++;
        temp_size /= 10;
    }
    /* close file */
    fclose(fp);

    /* file size as string */
    char str_fsize[j];
    sprintf(str_fsize, "%d", file_size); 
    
    /* create put request */
    uint32_t header_size = strlen("PUT") + strlen(put_name) + strlen(str_fsize) + 3;
    char put_header[header_size];
    bzero(put_header, header_size);
    strcpy(put_header, "PUT\n");
    strcat(put_header, put_name);
    strcat(put_header, "\n");
    strcat(put_header, str_fsize);
    strcat(put_header, "\n");

    /* send size of header */
    Send_Int(fd, header_size);
    /* send put request header */
    Send(fd, put_header, header_size);
    /* send put file */
    Send(fd, file_buf, file_size);

    /* get size of response header and create buffer */ 
    uint32_t rec_size = Receive_Int(fd);
    char response[rec_size];
    bzero(response, rec_size);

    /* get response */
    if (Receive(fd, response, rec_size) != 0)
        die("Put_file", "Connection closed while reading response");

    /* check response */
    if (strncmp(response, "OK\n", rec_size))
        die("Put_file server response error", response);
}
Esempio n. 30
0
	void Send(int i)
	{
		char buf[32];
		mir_snprintf(buf, "%d", i);
		Send(buf);
	}