void Membership::runLeaderElection()
{
	leader.active = false;
	bullied = false;

	if (members.size() < 2)
	{
		logFile << "No members, canceling leader election" << std::endl;
		return;
	}

	membersLock.lock();

	for (int i = 1; i < members.size(); ++i)
	{
		std::string other = members.at(i).ip_str;
		if ( isBiggerThanMine( other, my_ip_str) )
		{
			Message msg;
			msg.type = MSG_ELECTION;
			sendUDP( sockfd,  other, port, (char*)&msg, sizeof(Message) );
		}
	}

	membersLock.unlock();

	usleep(500); //Sleep one second

	if ( !bullied ) // Send all other that I am the leader
	{
		membersLock.lock();

		for (int i = 1; i < members.size(); ++i)
		{
			std::string other = members.at(i).ip_str;
			Message msg;
			msg.type = MSG_NEWLEADER;
			sendUDP( sockfd,  other, port, (char*)&msg, sizeof(Message) );
		}

		membersLock.unlock();

		leader = members.at(0);
		leader.active = true;
	}

/*
	Sleep
	check the queue

	if queue not empty, return
	else send NEWLEADER MSG  (I AM THE LEADER)
*/

}
void Membership::piggyPingMsg( Message msg, std::string sender )
{
    msg.type = MSG_PIGGY_ACK;
    //ipString2Char4(char42String(msg.carrierAdd), msg.carrierAdd); //Original Sender as carrier
    sendUDP( sockfd,  sender, port, (char*)&msg, sizeof(Message) );

    //Just in case, we can send the message back to the original sender
    // Because we can!
    std::string original = char42String(msg.carrierAdd);
    msg.type = MSG_ACK;
    sendUDP( sockfd,  original, port, (char*)&msg, sizeof(Message) );
}
void serialReadThread(void) {
  int UDPTransmitBufferLength;
  while(serialToUDP) {
    int c;
    c=getchar();
    if (c>=0) {
      //      printf("got char: %d\n", c);
      serialReadBuffer[serialReadBufferIn] = c;
      serialReadBufferIn = (serialReadBufferIn+1) % BUFFER_LENGTH;
      if(mavlink_parse(c)) {
	if(serialReadBufferIn >= serialReadBufferOut) {
	  // Non-wrap-round case.
	  memcpy(UDPTransmitBuffer, serialReadBuffer+serialReadBufferOut, serialReadBufferIn-serialReadBufferOut);
	  UDPTransmitBufferLength = serialReadBufferOut-serialReadBufferIn;
	} else {
	  // wrap-round case, eg. 
	  // 01234567
	  // xx---xxx
	  // in = 2, out=5
	  // copy 5-7 (3 bytes) to 0-2 and 0-2 (2 bytes) to 3-4
	  memcpy(UDPTransmitBuffer, serialReadBuffer+serialReadBufferOut, BUFFER_LENGTH-serialReadBufferOut);
	  memcpy(UDPTransmitBuffer+BUFFER_LENGTH-serialReadBufferOut, serialReadBuffer, serialReadBufferIn);
	  UDPTransmitBufferLength = BUFFER_LENGTH-serialReadBufferOut + serialReadBufferIn;
	}
	sendUDP(UDPTransmitBufferLength); // Will block until send, so afterwards the UDPBuffer is available again.
	// empty the buffer.
	serialReadBufferOut = serialReadBufferIn;
      }
    }
  }
}
Ejemplo n.º 4
0
int EthernetUDP::endPacket()
{
	if ( _sock == -1 )
		return -1;
	trace_debug("%s called", __func__);
	return sendUDP();
}
void Membership::spreadMessage(Message msg, int forwardNumber)
{
    //choose k or size-1 members
    membersLock.lock();
    std::vector<Node> selectedNode = members; 
    membersLock.unlock();

    if (selectedNode.size() < 3) return;   // Not enough nodes to do something
    // We need to remeve myself and the carrier from the possible list

    selectedNode.erase(selectedNode.begin()); // remove myself

    for (int i = 0; i < selectedNode.size(); ++i)
    {
        logFile << "comparing: " << selectedNode.at(i).ip_str << " " << char42String(msg.carrierAdd) << std::endl;
        if ( selectedNode.at(i).ip_str.compare(char42String(msg.carrierAdd)) == 0 )
        {
            selectedNode.erase(selectedNode.begin() + i); // remove carrier
            logFile << "equal" << std::endl;
            break;
        }
    }

    int k = forwardNumber == 0 ? K_FORWARD : forwardNumber;

    while (selectedNode.size() > 0 && k > 0)
    {
        int random = rand() % selectedNode.size();
        sendUDP( sockfd, selectedNode[random].ip_str, port, (char*)&msg, sizeof(Message) );
        selectedNode.erase(selectedNode.begin()+random);
        k--;
    }
}
void Membership::piggyAckMsg( Message msg, std::string sender )
{
    std::string target = char42String(msg.carrierAdd);
    msg.type = MSG_ACK;

    ipString2Char4(sender, msg.carrierAdd); //Dont care, but meh

    sendUDP( sockfd,  target, port, (char*)&msg, sizeof(Message) );
}
void Membership::piggyMsg( Message msg, std::string sender )
{
    std::string target = char42String(msg.carrierAdd);
    msg.type = MSG_PIGGY_PING;

    ipString2Char4(sender, msg.carrierAdd); //Original Sender as carrier

    sendUDP( sockfd,  target, port, (char*)&msg, sizeof(Message) );
    logFile << "Weired!: " << sender << " says that " << target << " did not responde..." << std::endl;
}
void Membership::electionMsg( Message msg, std::string sender )
{
	logFile << "Election received! I am gonna bully that guy :)" << std::endl;
    msg.type = MSG_BULLY;
    ipString2Char4(sender, msg.carrierAdd); //Dont care, but meh

    sendUDP( sockfd,  sender, port, (char*)&msg, sizeof(Message) );

	runLeaderElection();
}
Ejemplo n.º 9
0
void ClientManager::sendUDP(AdcCommand& cmd, const OnlineUser& user) {
	dcassert(cmd.getType() == AdcCommand::TYPE_UDP);
	if(!user.getIdentity().isUdpActive()) {
		cmd.setType(AdcCommand::TYPE_DIRECT);
		cmd.setTo(user.getIdentity().getSID());
		const_cast<Client&>(user.getClient()).send(cmd);
	} else {
		sendUDP(user.getIdentity().getIp(), user.getIdentity().getUdpPort(), cmd.toString(getMe()->getCID()));
	}
}
Ejemplo n.º 10
0
void processTFTP (TFTPDpkt * tp)
{
	register int nbtry;
	TFTPDpkt tftpd_pkt;

	if (!tftp_req)
		return;

	if (tftp_req->port == 0)
		tftp_req->port = tp->udphdr.src_port;

	if (tp->udphdr.iphdr.src_ip == tftp_req->server
		&& tp->udphdr.src_port == tftp_req->port) {
		if (tp->opcode == 3) {
			if (tp->num == tftp_req->bloc || tp->num == tftp_req->bloc - 1) {
				memset (&tftpd_pkt, 0, sizeof tftpd_pkt);
				tftpd_pkt.opcode = 4;
				tftpd_pkt.num = tp->num;
				for (nbtry = 4; nbtry; --nbtry) {
					if (sendUDP
						((UDPpkt *) & tftpd_pkt, 4, tftp_req->server,
						 TFTP_LOCAL_PORT, tp->udphdr.src_port) == 0)
						break;
					tick_Delay100ms (1);
				}
				if (nbtry == 0)
					printf ("TFTP: error sending ACK\n");
				if (tp->num == tftp_req->bloc) {
					register unsigned short len = tp->udphdr.length - 12;

					if (len) {
						memcpy ((void *) (tftp_req->addr + tftp_req->bcnt),
								tp->data, len);
						tftp_req->bcnt += len;
					}
					++tftp_req->bloc;
					putchar ("-\\|/"[tftp_req->bloc % 4]);
					putchar ('\b');
					if (tp->udphdr.length < 524) {
						tftp_req->sts = 1;
						printf ("TFTP: downloaded %d bytes\n",
								tftp_req->bcnt);
					}
				}
			}
		}
		else if (tp->opcode == 5) {
			printf ("TFTP error %d: %s\n", tp->num, tp->data);
			tftp_req->sts = -tp->num;
		}
	}
}
Ejemplo n.º 11
0
static NetworkTransmissionError SendDTLS(NetworkAddress * destAddress, const uint8_t * buffer, int bufferLength, void *context)
{
    NetworkTransmissionError result = NetworkTransmissionError_None;
    NetworkSocket * networkSocket = (NetworkSocket *)context;
    if (networkSocket)
    {
        if (!sendUDP(networkSocket, destAddress, buffer, bufferLength))
        {
            result = NetworkTransmissionError_TransmitBufferFull;
        }
    }
    return result;
}
Ejemplo n.º 12
0
int sendTFTPRequest (void)
{
	TFTPRpkt tftpr_pkt;
	unsigned short len;

	if (tftp_req) {
		memset (&tftpr_pkt, 0, sizeof tftpr_pkt);
		tftpr_pkt.opcode = 1;
		strcpy (tftpr_pkt.data, tftp_req->file);
		len = strlen (tftp_req->file) + 1;
		strcpy (tftpr_pkt.data + len, "octet");
		len += 8;				/* opcode size + octet\0 size */

		return sendUDP ((UDPpkt *) & tftpr_pkt, len, tftp_req->server,
						TFTP_LOCAL_PORT, TFTP_SRV_PORT);
	}
	return 1;
}
Ejemplo n.º 13
0
//f=1&d=1287370388&m=1234567890&z=XXX&from=sb->server
//心跳包
void MainWindow::heartbreak(float state)
{
    QString out;
    state=state;

    out.clear();

    out+="f=1&d=";
    out+=ui->comboBox->currentText();
    out+="&m=";
    out+=DEVPASSWORD;
    out+="&z=";
    out+=QString::number(state,'f',2);
    out+="&from=sb->server";

   // qDebug()<<out;
    sendUDP(out.toLatin1());
}
Ejemplo n.º 14
0
    void ProcessPerMessage::sendEthernet(Message * outboundMessage){
        int infoLength = 8;
        size_t headerLength = sizeof(int) + infoLength + sizeof(size_t);
        char* header = new char[headerLength];
        *((int*)header) = 2; //IP is the hlp
        memset(header + sizeof(int), 0, infoLength);
        *((size_t*)(header + sizeof(int) + infoLength)) = outboundMessage->msgLen();
        // printf("Eth header len %lu\n", headerLength);
        outboundMessage->msgAddHdr(header, headerLength);
        char * data = new char[1024];
        memset(data,0,1024);
        outboundMessage->msgFlat(data + sizeof(int));
        *((int*)data) = htonl(outboundMessage->msgLen());



        sendUDP(outSockFD, data, 1024);
    }
Ejemplo n.º 15
0
void ClientManager::on(NmdcSearch, Client* aClient, const string& aSeeker, int aSearchType, int64_t aSize,
									int aFileType, const string& aString) noexcept
{
	bool isPassive = (aSeeker.compare(0, 4, "Hub:") == 0);

	// We don't wan't to answer passive searches if we're in passive mode...
	if(isPassive && !ClientManager::getInstance()->isActive()) {
		return;
	}

	auto l = ShareManager::getInstance()->search(aString, aSearchType, aSize, aFileType, isPassive ? 5 : 10);
//		dcdebug("Found %d items (%s)\n", l.size(), aString.c_str());
	if(!l.empty()) {
		if(isPassive) {
			string name = aSeeker.substr(4);
			// Good, we have a passive seeker, those are easier...
			string str;
			for(const auto& sr: l) {
				str += sr->toSR(*aClient);
				str[str.length()-1] = 5;
				str += name;
				str += '|';
			}

			if(!str.empty())
				aClient->send(str);

		} else {
			string ip, port, file, proto, query, fragment;
			Util::decodeUrl(aSeeker, proto, ip, port, file, query, fragment);

			ip = Socket::resolve(ip, AF_INET);
			if(static_cast<NmdcHub*>(aClient)->isProtectedIP(ip))
				return;

			if(port.empty())
				port = "412";

			for(const auto& sr: l) {
				sendUDP(ip, port, sr->toSR(*aClient));
			}
		}
	}
}
Ejemplo n.º 16
0
bool NetworkSocket_Send(NetworkSocket * networkSocket, NetworkAddress * destAddress, uint8_t * buffer, int bufferLength)
{
    bool result = false;
    if (networkSocket)
    {
        networkSocket->LastError = NetworkSocketError_NoError;
        if (buffer && bufferLength > 0)
        {
            if ((networkSocket->SocketType & NetworkSocketType_UDP) == NetworkSocketType_UDP)
            {
                if (destAddress)
                {
                    if (destAddress->Secure)
                    {
                        int encryptedBytes;
                        if (DTLS_Encrypt(destAddress, buffer, bufferLength, encryptBuffer, ENCRYPT_BUFFER_LENGTH, &encryptedBytes, networkSocket))
                        {
                            buffer = encryptBuffer;
                            bufferLength = encryptedBytes;
                        }
                        else
                        {
                            bufferLength = 0;
                        }
                    }
                    if (bufferLength > 0)
                    {
                        result = sendUDP(networkSocket, destAddress, buffer, bufferLength);
                    }
                }
                else
                {
                    networkSocket->LastError = NetworkSocketError_InvalidArguments;
                }
            }
        }
        else
        {
            networkSocket->LastError = NetworkSocketError_InvalidArguments;
        }
    }
    return result;
}
Ejemplo n.º 17
0
//命令返回包
void MainWindow::cmdback(float state)
{
    QString out;
    state=state;

    out.clear();

    out+="f=b&d=";
    out+=device;
    out+="&m=";
    out+=DEVPASSWORD;
    out+="&n=";
    out+=account;
    out+="&com=";
    out+=command;
    out+="&from=sb->server";

   // qDebug()<<out;
    sendUDP(out.toLatin1());
}
Ejemplo n.º 18
0
/*****************************************************************
 * NAME: requestMembershipToLeader 
 *
 * DESCRIPTION: This function is designed to let member host 
 *              request leader node membership to Daisy 
 *              distributed system
 *              
 * PARAMETERS: 
 *            (char *) leaderPort: leader port number
 *            (char *) leaderIp: leader IP Address
 * 
 * RETURN:
 * (int) ZERO if success
 *       ERROR otherwise
 * 
 ****************************************************************/
int requestMembershipToLeader(int leaderPort, char *leaderIp)
{

    funcEntry(logF, ipAddress, "requestMembershipToLeader");

    int rc = SUCCESS,                            // Return code 
        i_rc,                                    // Temp RC
        numOfBytesSent;                          // Num of bytes sent

    char joinMessage[LONG_BUF_SZ],                // Buffer
         joinOperation[SMALL_BUF_SZ] = "JOIN$",  // Join prefix
         tableMessage[LONG_BUF_SZ];              // Table msg

    /*
     * Construct join message
     */
    printToLog(logF, ipAddress, "Message to be sent leader node is:");
    i_rc = create_message(tableMessage);
    sprintf(joinMessage, "%s%s", joinOperation, tableMessage);
    printToLog(logF, ipAddress, joinMessage);
    printToLog(logF, ipAddress, "Sending message to leader node");
    numOfBytesSent = sendUDP(leaderPort, leaderIp, joinMessage);
    sprintf(logMsg, "Num of bytes of join msg sent to leader: %d", numOfBytesSent);
    printToLog(logF, ipAddress, logMsg);
    // If number of bytes sent is 0
    if ( SUCCESS == numOfBytesSent)
    {
        rc = ERROR; 
        goto rtn;
    }
    printToLog(logF, ipAddress, "Join message sent successfully");

  rtn:
    funcExit(logF, ipAddress, "requestMembershipToLeader", rc);
    return rc;

} // End of requestMembershipToLeader()
Ejemplo n.º 19
0
/****************************************************************
 * NAME: sendFunc 
 *
 * DESCRIPTION: This is the function that takes care of sending
 *              heartbeats 
 *              
 * PARAMETERS: NONE 
 *
 * RETURN:
 * (int) ZERO if success
 *       ERROR otherwise
 * 
 ****************************************************************/
int sendFunc()
{

    funcEntry(logF, ipAddress, "sendFunc");

    int rc = SUCCESS,                      // Return code
        num_of_hosts_chosen,               // Number of hosts chosen 
        i_rc,                              // Temp RC
        numOfBytesSent,                    // Number of bytes sent
        portNo;                            // Port no

    register int counter;                  // Counter

    char msgToSend[LONG_BUF_SZ],           // Message to be sent
         ipAddr[SMALL_BUF_SZ],             // IP Address buffer
         portNoChar[SMALL_BUF_SZ];         // Port no

    struct two_hosts hosts[GOSSIP_HOSTS],  // An array of two_hosts
           *ptr;                           // Pointer to above
 
    ptr = hosts;

    while(1)
    {

        memset(msgToSend, '\0', LONG_BUF_SZ);

        // Debug
        printToLog(logF, "SENDOct3", msgToSend);

        initialize_two_hosts(ptr);
        num_of_hosts_chosen = choose_n_hosts(ptr, GOSSIP_HOSTS);

        sprintf(logMsg, "Number of hosts chosen to gossip: %d", num_of_hosts_chosen);
        printToLog(logF, ipAddress, logMsg);

        for ( counter = 0; counter < num_of_hosts_chosen; counter++ )
        {
            printToLog(logF, "PORT NO*****", hb_table[hosts[counter].host_id].port);
            strcpy(portNoChar, hb_table[hosts[counter].host_id].port);
            portNo = atoi(portNoChar);
            strcpy(ipAddr, hb_table[hosts[counter].host_id].IP);
            printToLog(logF, "IP ADDR*****", hb_table[hosts[counter].host_id].IP);
            // create message
            i_rc = create_message(msgToSend);
            if ( SUCCESS != i_rc )
            {
                printToLog(logF, ipAddress, "Unable to create message");
                continue;
            }

            // Debug
            printToLog(logF, "SENDOct3 after create_message", msgToSend);

            // Send UDP packets
            numOfBytesSent = sendUDP(portNo, ipAddr, msgToSend);
            // check if 0 bytes is sent
            if ( SUCCESS == numOfBytesSent )
            {
                printToLog(logF, ipAddress, "ZERO bytes sent");
                continue;
            }
            
            memset(msgToSend, '\0', LONG_BUF_SZ);
        } // End of for ( counter = 0; counter < num_of_hosts_chosen; counter++ )
        sleep(1);
    } // End of while 
    
  rtn:
    funcExit(logF, ipAddress, "sendFunc", rc);
    return rc;

} // End of sendFunc() 
Ejemplo n.º 20
0
int EthernetUDP::endPacket()
{
  return sendUDP(_sock);
}
 bool sendPacket( Packet* pack, const IPnPort& destination ) {
    sendUDP( pack, destination );
    return true;
 }
Ejemplo n.º 22
0
CSock::TSockResult	CUdpSimSock::send (const uint8 *buffer, uint32& len, bool /* throw_exception */)
{
	sendUDP (buffer, len);
	return CSock::Ok;
}
Ejemplo n.º 23
0
void CUdpSimSock::sendTo (const uint8 *buffer, uint32& len, const CInetAddress& addr)
{
	sendUDP (buffer, len, &addr);
}
Ejemplo n.º 24
0
 int BroadcastSock::sendMessage( const char* msg )
 {
     loadString((char*)msg);
     sendUDP();
     return 0;
 }
Ejemplo n.º 25
0
void Membership::pingMsg( Message msg, std::string sender )
{
	msg.type = MSG_ACK;
	sendUDP( sockfd,  sender, port, (char*)&msg, sizeof(Message) );
}
Ejemplo n.º 26
0
void Membership::detectThread()
{
    /*
    WHILE LOOP
        roundId++

        randomly select one node
        send ping message
        sleep(1)
        see msgQueue, search ack
        if(ack)
            cout<<alive
            sleep(4)
            continue
        
        send ping message to random K nodes (call spreadMessage())
        sleep(4)
        see msgQueue, search ack
        if(ack)
            cout<<alive
            continue
        
        if(!ack)
            cout<<fail
            delete node
            send fail message to other nodes
            continue
    */
    bool flagFail = false;
    Node failedNode;
    while(!killDetectingThread)
    {
  
        roundId = (roundId+1)%255;

        if (roundId % 5 == 0)
        {
        	checkLeader();
        }

        logFile<< std::endl << "Detection Thread - Round: "<< roundId << " ------------" << std::endl;
        logFile<<printMember();
        
        if(members.size() < 2)
        {
            usleep(5 * MAX_LATENCY);
            flagFail = false;
            continue;
        }

        int select = rand()%(members.size()-1) + 1;
        Node theNode = members[select];

        if (flagFail == true)
        {
            theNode = failedNode;
        }

        Message msg;
        msg.type = MSG_PING;
        msg.TTL = 0;
        msg.roundId = roundId;
        ipString2Char4(theNode.ip_str, msg.carrierAdd);
        msg.timeStamp = 0;

        logFile<<"detectThread: checking alive or not for "<<theNode.ip_str<<" "<<theNode.timeStamp<<std::endl;
        sendUDP(sockfd, theNode.ip_str, port, (char*)&msg, sizeof(Message));

        bool acked = false;

        if (queueSize() > 10){
            std::cout << "Warning!!! queueSize = " << queueSize() << std::endl;
        }

        usleep(MAX_LATENCY);

        msgQueueLock.lock();
        acked = ackMsgQueue();
        msgQueueLock.unlock();

        static int count = 0;
        if(acked){
            logFile<<"detectThread: node alive: "<<theNode.ip_str<<" "<<theNode.timeStamp<<std::endl;
            flagFail = false;
            usleep(4 * MAX_LATENCY);     
            continue;       
        }

        logFile<<"Hey!!! Node "<<theNode.ip_str<<" did not respond the first time!" << std::endl;

        msg.type = MSG_PIGGY;
        msg.TTL = 0;
        spreadMessage(msg,3);
        usleep(4 * MAX_LATENCY);

        msgQueueLock.lock();
        acked = ackMsgQueue();
        msgQueueLock.unlock();

        if(acked){
            logFile<<"detectThread: second round found node alive: "<<theNode.ip_str<<" "<<theNode.timeStamp<<std::endl;
            flagFail = false;
            continue;
        }
        else{
            logFile<< "detectThread: No ack received: node failed: "<<theNode.ip_str<<" "<<theNode.timeStamp<<std::endl;
            
            if (flagFail == true)
            {
                logFile<< "detectThread: No ack received: node failed: "<<theNode.ip_str<<" "<<theNode.timeStamp<<std::endl;
                failMember(theNode.ip_str, theNode.timeStamp);

                Message failMsg;
                failMsg.type = MSG_FAIL;
                failMsg.roundId = roundId;
                ipString2Char4(theNode.ip_str, failMsg.carrierAdd);
                failMsg.timeStamp = theNode.timeStamp;
                failMsg.TTL = 3;

                spreadMessage(failMsg);
                flagFail = false;
            }
            else
            {
                logFile<< "detectThread: Robust 2: It is alive: "<<theNode.ip_str<<" "<<theNode.timeStamp<<std::endl;
                failedNode = theNode;
                flagFail = true;

            }


            continue;
        }
    }
}