Пример #1
0
bool CalculibProtocol::sendTypedData(unsigned char type, CalculibBuffer * toSend)
{
    //allows to use NULL
    CalculibBuffer emptyBuffer;
    emptyBuffer.size = 0;
    if(toSend == NULL)
    {
        toSend = &emptyBuffer;
    }
        
    if(socket->getMaxSendBufferSize() - socket->getSendBuffer()->size < 1+4+toSend->size+1) // built packet size
    {
        return true; // out of space
    }
    
    CalculibBuffer inSocketBuffer; // writes directly in the socket's send buffer
    inSocketBuffer.buffer = socket->getSendBuffer()->buffer + socket->getSendBuffer()->size;
    inSocketBuffer.size = socket->getMaxSendBufferSize() - socket->getSendBuffer()->size;
    
    if(buildPacket(&inSocketBuffer,type,toSend))
    {
        printf("Error packing, this is impossible !\n");
        return true;
    }
    
    socket->getSendBuffer()->size += inSocketBuffer.size; // manually add to the size (buildPacket wrote in the buffer)
    return false;
}
Пример #2
0
AREXPORT void ArServerHandlerPopup::netPopupList(ArServerClient *client,
						 ArNetPacket *packet)
{
  ArLog::log(ArLog::Normal, "Sending popup list");

  std::map<ArTypes::Byte4, PopupData *>::iterator it;
  ArNetPacket sendingPacket;
  PopupData *popupData;

  myDataMutex.lock();
  for (it = myMap.begin(); it != myMap.end(); it++)
  {
    popupData = (*it).second;
    sendingPacket.empty();

    ArLog::log(ArLog::Normal, "Sending popup %d", popupData->myID);
    buildPacket(&sendingPacket, popupData);
    sendingPacket.setCommand(myServer->findCommandFromName("popupCreate"));

    client->sendPacketTcp(&sendingPacket);
  }

  sendingPacket.empty();
  client->sendPacketTcp(&sendingPacket);
  ArLog::log(ArLog::Normal, "Sent popups");
  myDataMutex.unlock();
}
Пример #3
0
PinoPacketSender::PinoPacketSender(char type, list<PinoField> fields) //Query Comment Request with list of params
{
	if (type != PostCommentReq)
	{
		cout << "PinoPacket: invalid type!" << endl;
	}
	string b_str = buildPacketUnitBody(fields);
	buildPacket(PostCommentReq, b_str);
}
Пример #4
0
PinoPacketSender::PinoPacketSender(char type, PinoComment cmmt)		//PostComment
{
	if (type != PostCommentReq)
	{
		cout << "PinoPacket: Invald type!" << endl;
	}
	string b_str = buildPacketBody(cmmt);	
	buildPacket(PostCommentReq, b_str);
}
Пример #5
0
/************
* readPacket()
***********/
int readPacket( int sd, char *buffer, int bufferSize, struct packet *p )
{
	int  bytes_read;
	
	bytes_read = recvfrom ( sd, buffer, bufferSize, MSG_DONTWAIT, 0, 0 );
	if( bytes_read > 0 )
		buildPacket( buffer, p );
	
	return bytes_read;
}
Пример #6
0
PinoPacketSender::PinoPacketSender(char type, string url) 			//QueryCommentReq
{
	if (type != QueryCommentReq)
	{
		cout << "PinoPacket: invalid type." << endl;
	}
	list<PinoField> cflst;
	cflst.push_back(PinoField(FIELD_TYPE_URL, url));
	string b_str = buildPacketUnitBody(cflst);
	buildPacket(QueryCommentReq, b_str);
}
Пример #7
0
void
ObjectAccessor::buildUpdateObject(Object *obj, UpdateDataMapType &update_players)
{
    if(obj->isType(TYPEMASK_ITEM))
    {
        if(Player *owner = ((Item*)obj)->GetOwner())
           buildPacket(owner, obj, update_players);
    }
    else
        buildChangeObjectForPlayer((WorldObject*)obj, update_players);
}
Пример #8
0
PinoPacketSender::PinoPacketSender(char type, string url, list<PinoComment> clst)		// QueryCommentResp
{
	if (type != QueryCommentResp)
	{
		cout << "PinoPacket: invald type!" << endl;
	}
	if (url.length() == 0 || clst.empty())
	{
		cout << "PinoPacket: Invalid parameter." << endl;
	}

	string b_str = buildPacketBody(clst);
	buildPacket(QueryCommentResp, b_str);
}
Пример #9
0
PinoPacketSender::PinoPacketSender(char type, string url, string author, string content)	//PostComment
{
	if (type != PostCommentReq)
	{
		cout << "PinoPacket: invalid type!" << endl;
	}
       
	if (url.length() == 0 || author.empty() || content.empty())
	{
		cout << "URL/author/content cannot be empty!" << endl;
	}

	string b_str = buildPacketBody(PinoComment(url, author, content));
	buildPacket(PostCommentReq, b_str);
}
Пример #10
0
TCPSession::TCPSession(const SocketAddress& peerAddress, SocketFile& file, Protocol& protocol, Invoker& invoker) : _timeout(protocol.getNumber<UInt32>("timeout") * 1000), _client(peerAddress, file, invoker.sockets), Session(protocol, invoker) {
	((SocketAddress&)peer.address).set(peerAddress);

	_receptions.emplace_back(0);

	onInitParameters = [this](const Parameters& parameters) {
		if (parameters.getNumber("timeout", _timeout))
			_timeout *= 1000;
	};

	onError = [this](const Exception& ex) { WARN(name(), ", ", ex.error()); };

	onData = [this](PoolBuffer& pBuffer)->UInt32 {
		if (died)
			return 0;
		UInt32 size(pBuffer->size());
		PacketReader packet(pBuffer->data(), size);
		UInt32 receptions(_receptions.back());
		if (!buildPacket(pBuffer,packet)) {
			if (_receptions.size()>1 && _receptions.front() > 0 && (--_receptions.front()) == 0) {
				_receptions.pop_front();
				flush();
			}
			return size;
		}

		bool noDecoding(receptions == _receptions.back());
	
		UInt32 rest = size - packet.position() - packet.available();
		if (rest==0)
			_receptions.emplace_back(0);

		if (noDecoding) {
			++_receptions.back();
			receive(packet);
		}

		return rest;
	};

	onDisconnection = [this](const SocketAddress&) { kill(SOCKET_DEATH); };

	peer.OnInitParameters::subscribe(onInitParameters);
	_client.OnError::subscribe(onError);
	_client.OnDisconnection::subscribe(onDisconnection);
	_client.OnData::subscribe(onData);
}
Пример #11
0
void ClusterMembership::SendAnnouncement()
{
        struct sockaddr_in dst;
        dst.sin_family = AF_INET;
        dst.sin_port = htons(ourport);
        dst.sin_addr = multiaddr;
        const int buflen = 1400;
        char msg[buflen];
        std::memset(msg,0,buflen);
	int msglen = buildPacket(msg, buflen);

        int res = sendto(sock, msg, msglen, 0 /* flags */,
                (struct sockaddr *) & dst, sizeof(dst));
        if (res != msglen) {
                std::perror("sendto");
		throw std::runtime_error("sendto");
        }
}
Пример #12
0
bool BankSession::sendP(long int &csock, void* packet, std::string command)
{
    if(!this->key)
    {
        return false;
    }

    bankNonce = makeHash(randomString(128));
    command = command + "," + atmNonce + "," + bankNonce;
    if(command.size() >= 460)
    {
        return false;
    }
    buildPacket((char*)packet, command);
    if(!encryptPacket((char*)packet,this->key))
    {
        return false;
    }

    return sendPacket(csock, packet);
}
Пример #13
0
/*-----------------------------------------------------------------------------*/
int main(int argc, char *argv[]) {

        Input input = validateInput(argc, argv);
	printf("awget:\n\tRequest: %s\n\t", input.URL);

	char ** fileLines = readFile(input.filename);	

	printf("chainlist is\n\t");
        for(int j = 1; fileLines[j] != NULL; j++) {
	    printf("%s\n\t", fileLines[j]);
	}

	Packet * aPacket = buildPacket(fileLines, input.URL);

	int randStepNum = getRandStepNum(aPacket->chainFile[0]); //Get random stepping stone number
	
	char * steppingStone = fileLines[randStepNum]; //Get random stepping stone

	printf("next SS is %s\n\t", steppingStone);

	//Connect to stepping stone
        int socketfd = setupSocket(getIP(steppingStone), atoi(getPort(steppingStone)));

	//Remove stepping stone from file
	removeSS(randStepNum, aPacket); 

	//Write to stepping stone
	socketfd = writeSocket(socketfd, aPacket);

	printf("waiting for file...\n..\n");	

	//Read the data
	char *filename = getFilename(input.URL);
	makeFile(socketfd, filename);
	printf("\tReceived file <%s>\n\tGoodbye!\n", filename);
	close(socketfd);
        free (aPacket);
}
Пример #14
0
/**
   Creates a popup, for information about whats in the popup see
   ArServerHandlerPopupInfo... this just describes what happens with
   the popup...  

   So you pass in a popupInfo for the popup you want and a functor to
   call when buttons in the popup are pushed, this returns an id for
   that popup, which you can use to cancel the popup and so you know
   which popup this is.... the callback (if there is one) will be
   called when the popup has a button pushed with the id and the
   number of the button or -1 if the popup timed out or -2 if it was
   canceled.  The popup has a timeout, so that if no clients are
   connected watching for popups or if no one is paying attention that
   things can move on easily.

   @param popupInfo the information that describes the popup... this
   class makes a copy of the information so you can do whatever you
   want with the information after you've called this function (ie
   change the button and call it again or whatever)

   @param callback The class will call this function when one of the
   buttons is pressed in the popup on one of the clients, the callback
   will be called with the long int being the ID, and the int being
   the button that is pushed (or -1 if the timeout happened or -2 if
   it was closed)
 **/
AREXPORT ArTypes::Byte4 ArServerHandlerPopup::createPopup(
	ArServerHandlerPopupInfo *popupInfo, 
	ArFunctor2<ArTypes::Byte4, int> *callback)
{
  PopupData *popupData;
  ArTypes::Byte4 retID;

  myDataMutex.lock();
  // first find a good id
  myLastID++;
  if (myLastID < 0)
    myLastID = 1;
  //printf("Checking if id %u is good\n", myLastID);
  while (myMap.find(myLastID) != myMap.end())
  {
    myLastID++;
    if (myLastID < 0)
      myLastID = 1;
  }
  //printf("Got id %d\n", myLastID);
  popupData = new PopupData(popupInfo, myLastID, callback);
  myMap[myLastID] = popupData;

  ArNetPacket sendingPacket;
  buildPacket(&sendingPacket, popupData);

  /*
  printf("!!! %s %s %s\n", 
	 popupData->myPopupInfo->getButton0Label(),
	 popupData->myPopupInfo->getButton1Label(),
	 popupData->myPopupInfo->getButton2Label());
  */
  retID = myLastID;
  myDataMutex.unlock();
  myServer->broadcastPacketTcp(&sendingPacket, "popupCreate");
  return retID;
}
Пример #15
0
	//this function appends packets to the end of the packet_list.
	void Packetizer::appendPackets () {
		size_t i;
		for (i = packet_list.size (); i < PACKET_LIST_MAX; i++)
			packet_list.push_back (buildPacket ());
	}
Пример #16
0
void* client_thread(void* arg)
{
    BankSocketThread* bankSocketThread = (BankSocketThread*) arg;
    Bank* bank = bankSocketThread->bank;
    BankSession* bankSession = new BankSession();
    bankSession->state = 0;
    bankSession->bank = bank;
    bankSession->key = 0;

    long int csock = (long int)*(bankSocketThread->csock);
    
    printf("[bank] client ID #%ld connected\n", csock);
    
    //input loop
    int length;
    char packet[1024];
    bool fatalError = false;
    std::vector<std::string> tokens;
    while(1)
    {
        fatalError = false;
        tokens.clear();
        
        if(!listenPacket(csock, packet))
        {
            printf("[bank] fail to read packet\n");
            break;
        }
        if(!bankSession->key)
        {
            if(bankSession->state != 0)
            {
                printf("[error] Unexpected state\n");
                break;
            }
            for(unsigned int i = 0; i < bank->keys.size(); ++i)
            {
                if(bank->keysInUse[i])
                {
                    continue;
                }
                if(decryptPacket((char*)packet,bank->keys[i])
                    && std::string(packet).substr(0,9) == "handshake")
                {
                    bankSession->key = bank->keys[i];
                    bank->keysInUse[i] = true;
                    break;
                }
            }
            if(!bankSession->key)
            {
                printf("[error] Key not found.\n");
                break;
            }
        } else {
            if(!decryptPacket((char*)packet, bankSession->key))
            {
                printf("[error] Invalid key\n");
                break;
            }
        }    

        //Parse the packet
        //std::string strPacket = packet;
        split(std::string(packet),',', tokens);

        //We should get something, if not ignore this packet
        if(tokens.size() < 1)
        {
            continue;
        }

        if(tokens[0] == "logout")
        {
            bankSession->endSession();
            break;
        }

        //Now we're compare what we go to what state we expect to be in
        switch(bankSession->state)
        {
            case 0:
            case 1:
                if(tokens.size() == 2 && tokens[0] == "handshake" && tokens[1].size() == 128)
                {
                    bankSession->atmNonce = tokens[1];
                    bankSession->bankNonce = makeHash(randomString(128));
                    if(bankSession->bankNonce.size() == 0)
                    {
                        printf("Unexpected error\n");
                        fatalError = true;
                        break;
                    }
                    buildPacket(packet, "handshakeResponse," + bankSession->atmNonce + "," + bankSession->bankNonce);
                    if(!encryptPacket((char*)packet,bankSession->key))
                    {
                        printf("Unexpected error\n");
                        fatalError = true;
                        break;
                    }
                    if(!sendPacket(csock, packet))
                    {
                        printf("Unexpected error\n");
                        fatalError = true;
                        break;
                    }
                    bankSession->state = 2;
                }
                break;
            //Expecting a login
            case 2:
                if(!bankSession->validateNonce(std::string(packet)))
                {
                    printf("Unexpected error\n");
                    fatalError = true;
                    break;
                }
                if(tokens.size() == 5 && tokens[0] == "login" && tokens[1].size() == 128)
                {
                    //Now we'll try to find the account
                    //bankSession->account = bank->tryLoginHash(tokens[1]);
                    bankSession->account = bank->getAccountByName(tokens[2]);
                    if(!bankSession->account || !bankSession->account->tryHash(tokens[1]))
                    {
                        //Failed login
                        //TODO Blacklist hash
                        bankSession->error = true;
                        //printf("[notice] Failed login!\n");
                    }
                    bankSession->account->inUse = true;
                    bankSession->state = 5;
                    if(!bankSession->sendP(csock,packet, "ack"))
                    {
                        printf("Unexpected error!\n");
                        fatalError = true;
                        break;
                    }
                }
                break;
            case 5:
                bool returnBalance = false;
                bankSession->state = 4;
                if(bankSession->error)
                {
                    returnBalance = false;
                } 
                else if(tokens.size() == 3 && tokens[0] == "balance")
                {
                    returnBalance = true;
                }
                else if(tokens.size() == 4 && tokens[0] == "withdraw" && isDouble(tokens[1]))
                {
                    double amount = atof(tokens[1].c_str());
                    if(!bankSession->account->Withdraw(amount))
                    {
                        printf("[error] Failed withdraw\n");
                        returnBalance = false;
                        bankSession->error = true;
                    }
                    returnBalance = true;
                }
                else if(tokens.size() == 5 && tokens[0] == "transfer" && !isDouble(tokens[1])
                    && isDouble(tokens[2]))
                {
                    Account* accountTo = bank->getAccountByName(tokens[1]);
                    double amount = atof(tokens[2].c_str());
                    if(!bankSession->account->Transfer(amount, accountTo))
                    {
                        printf("[error] Failed transfer\n");
                        returnBalance = false;
                        bankSession->error = true;
                    }
                    returnBalance = true;
                }

                if(bankSession->error)
                {
                    bankSession->sendP(csock, packet, "denied");
                }
                else if(returnBalance)
                {
                    char moneyStr[256];
                    sprintf(moneyStr,"%.2Lf",bankSession->account->getBalance());
                    bankSession->sendP(csock, packet, std::string(moneyStr));
                }

                //Reset back to initial state
                bankSession->endSession();
                break;
        }
        
        if(fatalError)
        {
            bankSession->endSession();
            break;
        }
    }

    bankSession->endSession();

    printf("[bank] client ID #%ld disconnected\n", csock);

    close(csock);
    delete bankSession;
    return NULL;
}
Пример #17
0
uint8_t sendPacket(uint8_t* context, uint32_t len)
{
    uint32_t sendlen = buildPacket(context,len,packet,512);
    vUARTSend(packet,sendlen);
    return len;
}
Пример #18
0
Packet::Packet(char type, int origin, int target, const char *data) : _type(type), _origin(origin), _target(target), _data(data), _packet(NULL)
{
	buildPacket(type, origin, target, data);
}
Пример #19
0
void PacketHandler::buildModePacket(Packet *packet, char *data, int len, char type, char mode)
{
	buildPacket(packet, data, len, type);
	packet->setInfo(mode);
}